repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/modules/tls.py
validate
def validate(cert, ca_name, crl_file): ''' .. versionadded:: Neon Validate a certificate against a given CA/CRL. cert path to the certifiate PEM file or string ca_name name of the CA crl_file full path to the CRL file ''' store = OpenSSL.crypto.X509Store() cert_obj = _read_cert(cert) if cert_obj is None: raise CommandExecutionError( 'Failed to read cert from {0}, see log for details'.format(cert) ) ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name) ca_cert = _read_cert('{0}/{1}_ca_cert.crt'.format(ca_dir, ca_name)) store.add_cert(ca_cert) # These flags tell OpenSSL to check the leaf as well as the # entire cert chain. X509StoreFlags = OpenSSL.crypto.X509StoreFlags store.set_flags(X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL) if crl_file is None: crl = OpenSSL.crypto.CRL() else: with salt.utils.files.fopen(crl_file) as fhr: crl = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, fhr.read()) store.add_crl(crl) context = OpenSSL.crypto.X509StoreContext(store, cert_obj) ret = {} try: context.verify_certificate() ret['valid'] = True except OpenSSL.crypto.X509StoreContextError as e: ret['error'] = str(e) ret['error_cert'] = e.certificate ret['valid'] = False return ret
python
def validate(cert, ca_name, crl_file): ''' .. versionadded:: Neon Validate a certificate against a given CA/CRL. cert path to the certifiate PEM file or string ca_name name of the CA crl_file full path to the CRL file ''' store = OpenSSL.crypto.X509Store() cert_obj = _read_cert(cert) if cert_obj is None: raise CommandExecutionError( 'Failed to read cert from {0}, see log for details'.format(cert) ) ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name) ca_cert = _read_cert('{0}/{1}_ca_cert.crt'.format(ca_dir, ca_name)) store.add_cert(ca_cert) # These flags tell OpenSSL to check the leaf as well as the # entire cert chain. X509StoreFlags = OpenSSL.crypto.X509StoreFlags store.set_flags(X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL) if crl_file is None: crl = OpenSSL.crypto.CRL() else: with salt.utils.files.fopen(crl_file) as fhr: crl = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, fhr.read()) store.add_crl(crl) context = OpenSSL.crypto.X509StoreContext(store, cert_obj) ret = {} try: context.verify_certificate() ret['valid'] = True except OpenSSL.crypto.X509StoreContextError as e: ret['error'] = str(e) ret['error_cert'] = e.certificate ret['valid'] = False return ret
[ "def", "validate", "(", "cert", ",", "ca_name", ",", "crl_file", ")", ":", "store", "=", "OpenSSL", ".", "crypto", ".", "X509Store", "(", ")", "cert_obj", "=", "_read_cert", "(", "cert", ")", "if", "cert_obj", "is", "None", ":", "raise", "CommandExecutio...
.. versionadded:: Neon Validate a certificate against a given CA/CRL. cert path to the certifiate PEM file or string ca_name name of the CA crl_file full path to the CRL file
[ "..", "versionadded", "::", "Neon" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L566-L609
train
saltstack/salt
salt/modules/tls.py
_get_expiration_date
def _get_expiration_date(cert): ''' Returns a datetime.datetime object ''' cert_obj = _read_cert(cert) if cert_obj is None: raise CommandExecutionError( 'Failed to read cert from {0}, see log for details'.format(cert) ) return datetime.strptime( salt.utils.stringutils.to_str(cert_obj.get_notAfter()), four_digit_year_fmt )
python
def _get_expiration_date(cert): ''' Returns a datetime.datetime object ''' cert_obj = _read_cert(cert) if cert_obj is None: raise CommandExecutionError( 'Failed to read cert from {0}, see log for details'.format(cert) ) return datetime.strptime( salt.utils.stringutils.to_str(cert_obj.get_notAfter()), four_digit_year_fmt )
[ "def", "_get_expiration_date", "(", "cert", ")", ":", "cert_obj", "=", "_read_cert", "(", "cert", ")", "if", "cert_obj", "is", "None", ":", "raise", "CommandExecutionError", "(", "'Failed to read cert from {0}, see log for details'", ".", "format", "(", "cert", ")",...
Returns a datetime.datetime object
[ "Returns", "a", "datetime", ".", "datetime", "object" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L612-L626
train
saltstack/salt
salt/modules/tls.py
create_ca
def create_ca(ca_name, bits=2048, days=365, CN='localhost', C='US', ST='Utah', L='Salt Lake City', O='SaltStack', OU=None, emailAddress=None, fixmode=False, cacert_path=None, ca_filename=None, digest='sha256', onlyif=None, unless=None, replace=False): ''' Create a Certificate Authority (CA) ca_name name of the CA bits number of RSA key bits, default is 2048 days number of days the CA will be valid, default is 365 CN common name in the request, default is "localhost" C country, default is "US" ST state, default is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" OU organizational unit, default is None emailAddress email address for the CA owner, default is None cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 Writes out a CA certificate based upon defined config values. If the file already exists, the function just returns assuming the CA certificate already exists. If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' the resulting CA, and corresponding key, would be written in the following location:: /etc/pki/koji/koji_ca_cert.crt /etc/pki/koji/koji_ca_cert.key CLI Example: .. code-block:: bash salt '*' tls.create_ca test_ca ''' status = _check_onlyif_unless(onlyif, unless) if status is not None: return None set_ca_path(cacert_path) if not ca_filename: ca_filename = '{0}_ca_cert'.format(ca_name) certp = '{0}/{1}/{2}.crt'.format( cert_base_path(), ca_name, ca_filename) ca_keyp = '{0}/{1}/{2}.key'.format( cert_base_path(), ca_name, ca_filename) if not replace and not fixmode and ca_exists(ca_name, ca_filename=ca_filename): return 'Certificate for CA named "{0}" already exists'.format(ca_name) if fixmode and not os.path.exists(certp): raise ValueError('{0} does not exists, can\'t fix'.format(certp)) if not os.path.exists('{0}/{1}'.format( cert_base_path(), ca_name) ): os.makedirs('{0}/{1}'.format(cert_base_path(), ca_name)) # try to reuse existing ssl key key = None if os.path.exists(ca_keyp): with salt.utils.files.fopen(ca_keyp) as fic2: # try to determine the key bits try: key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fic2.read()) except OpenSSL.crypto.Error as err: log.warning('Error loading existing private key' ' %s, generating a new key: %s', ca_keyp, err) bck = "{0}.unloadable.{1}".format(ca_keyp, datetime.utcnow().strftime("%Y%m%d%H%M%S")) log.info('Saving unloadable CA ssl key in %s', bck) os.rename(ca_keyp, bck) if not key: key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, bits) ca = OpenSSL.crypto.X509() ca.set_version(2) ca.set_serial_number(_new_serial(ca_name)) ca.get_subject().C = C ca.get_subject().ST = ST ca.get_subject().L = L ca.get_subject().O = O if OU: ca.get_subject().OU = OU ca.get_subject().CN = CN if emailAddress: ca.get_subject().emailAddress = emailAddress ca.gmtime_adj_notBefore(0) ca.gmtime_adj_notAfter(int(days) * 24 * 60 * 60) ca.set_issuer(ca.get_subject()) ca.set_pubkey(key) if X509_EXT_ENABLED: ca.add_extensions([ OpenSSL.crypto.X509Extension( b'basicConstraints', True, b'CA:TRUE, pathlen:0'), OpenSSL.crypto.X509Extension( b'keyUsage', True, b'keyCertSign, cRLSign'), OpenSSL.crypto.X509Extension( b'subjectKeyIdentifier', False, b'hash', subject=ca)]) ca.add_extensions([ OpenSSL.crypto.X509Extension( b'authorityKeyIdentifier', False, b'issuer:always,keyid:always', issuer=ca)]) ca.sign(key, salt.utils.stringutils.to_str(digest)) # always backup existing keys in case keycontent = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) write_key = True if os.path.exists(ca_keyp): bck = "{0}.{1}".format(ca_keyp, datetime.utcnow().strftime( "%Y%m%d%H%M%S")) with salt.utils.files.fopen(ca_keyp) as fic: old_key = salt.utils.stringutils.to_unicode(fic.read()).strip() if old_key.strip() == keycontent.strip(): write_key = False else: log.info('Saving old CA ssl key in %s', bck) with salt.utils.files.fopen(bck, 'w') as bckf: bckf.write(old_key) os.chmod(bck, 0o600) if write_key: with salt.utils.files.fopen(ca_keyp, 'wb') as ca_key: ca_key.write(salt.utils.stringutils.to_bytes(keycontent)) with salt.utils.files.fopen(certp, 'wb') as ca_crt: ca_crt.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_PEM, ca ) ) ) _write_cert_to_database(ca_name, ca) ret = ('Created Private Key: "{0}/{1}/{2}.key." ').format( cert_base_path(), ca_name, ca_filename) ret += ('Created CA "{0}": "{1}/{0}/{2}.crt."').format( ca_name, cert_base_path(), ca_filename) return ret
python
def create_ca(ca_name, bits=2048, days=365, CN='localhost', C='US', ST='Utah', L='Salt Lake City', O='SaltStack', OU=None, emailAddress=None, fixmode=False, cacert_path=None, ca_filename=None, digest='sha256', onlyif=None, unless=None, replace=False): ''' Create a Certificate Authority (CA) ca_name name of the CA bits number of RSA key bits, default is 2048 days number of days the CA will be valid, default is 365 CN common name in the request, default is "localhost" C country, default is "US" ST state, default is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" OU organizational unit, default is None emailAddress email address for the CA owner, default is None cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 Writes out a CA certificate based upon defined config values. If the file already exists, the function just returns assuming the CA certificate already exists. If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' the resulting CA, and corresponding key, would be written in the following location:: /etc/pki/koji/koji_ca_cert.crt /etc/pki/koji/koji_ca_cert.key CLI Example: .. code-block:: bash salt '*' tls.create_ca test_ca ''' status = _check_onlyif_unless(onlyif, unless) if status is not None: return None set_ca_path(cacert_path) if not ca_filename: ca_filename = '{0}_ca_cert'.format(ca_name) certp = '{0}/{1}/{2}.crt'.format( cert_base_path(), ca_name, ca_filename) ca_keyp = '{0}/{1}/{2}.key'.format( cert_base_path(), ca_name, ca_filename) if not replace and not fixmode and ca_exists(ca_name, ca_filename=ca_filename): return 'Certificate for CA named "{0}" already exists'.format(ca_name) if fixmode and not os.path.exists(certp): raise ValueError('{0} does not exists, can\'t fix'.format(certp)) if not os.path.exists('{0}/{1}'.format( cert_base_path(), ca_name) ): os.makedirs('{0}/{1}'.format(cert_base_path(), ca_name)) # try to reuse existing ssl key key = None if os.path.exists(ca_keyp): with salt.utils.files.fopen(ca_keyp) as fic2: # try to determine the key bits try: key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fic2.read()) except OpenSSL.crypto.Error as err: log.warning('Error loading existing private key' ' %s, generating a new key: %s', ca_keyp, err) bck = "{0}.unloadable.{1}".format(ca_keyp, datetime.utcnow().strftime("%Y%m%d%H%M%S")) log.info('Saving unloadable CA ssl key in %s', bck) os.rename(ca_keyp, bck) if not key: key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, bits) ca = OpenSSL.crypto.X509() ca.set_version(2) ca.set_serial_number(_new_serial(ca_name)) ca.get_subject().C = C ca.get_subject().ST = ST ca.get_subject().L = L ca.get_subject().O = O if OU: ca.get_subject().OU = OU ca.get_subject().CN = CN if emailAddress: ca.get_subject().emailAddress = emailAddress ca.gmtime_adj_notBefore(0) ca.gmtime_adj_notAfter(int(days) * 24 * 60 * 60) ca.set_issuer(ca.get_subject()) ca.set_pubkey(key) if X509_EXT_ENABLED: ca.add_extensions([ OpenSSL.crypto.X509Extension( b'basicConstraints', True, b'CA:TRUE, pathlen:0'), OpenSSL.crypto.X509Extension( b'keyUsage', True, b'keyCertSign, cRLSign'), OpenSSL.crypto.X509Extension( b'subjectKeyIdentifier', False, b'hash', subject=ca)]) ca.add_extensions([ OpenSSL.crypto.X509Extension( b'authorityKeyIdentifier', False, b'issuer:always,keyid:always', issuer=ca)]) ca.sign(key, salt.utils.stringutils.to_str(digest)) # always backup existing keys in case keycontent = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) write_key = True if os.path.exists(ca_keyp): bck = "{0}.{1}".format(ca_keyp, datetime.utcnow().strftime( "%Y%m%d%H%M%S")) with salt.utils.files.fopen(ca_keyp) as fic: old_key = salt.utils.stringutils.to_unicode(fic.read()).strip() if old_key.strip() == keycontent.strip(): write_key = False else: log.info('Saving old CA ssl key in %s', bck) with salt.utils.files.fopen(bck, 'w') as bckf: bckf.write(old_key) os.chmod(bck, 0o600) if write_key: with salt.utils.files.fopen(ca_keyp, 'wb') as ca_key: ca_key.write(salt.utils.stringutils.to_bytes(keycontent)) with salt.utils.files.fopen(certp, 'wb') as ca_crt: ca_crt.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_PEM, ca ) ) ) _write_cert_to_database(ca_name, ca) ret = ('Created Private Key: "{0}/{1}/{2}.key." ').format( cert_base_path(), ca_name, ca_filename) ret += ('Created CA "{0}": "{1}/{0}/{2}.crt."').format( ca_name, cert_base_path(), ca_filename) return ret
[ "def", "create_ca", "(", "ca_name", ",", "bits", "=", "2048", ",", "days", "=", "365", ",", "CN", "=", "'localhost'", ",", "C", "=", "'US'", ",", "ST", "=", "'Utah'", ",", "L", "=", "'Salt Lake City'", ",", "O", "=", "'SaltStack'", ",", "OU", "=", ...
Create a Certificate Authority (CA) ca_name name of the CA bits number of RSA key bits, default is 2048 days number of days the CA will be valid, default is 365 CN common name in the request, default is "localhost" C country, default is "US" ST state, default is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" OU organizational unit, default is None emailAddress email address for the CA owner, default is None cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 Writes out a CA certificate based upon defined config values. If the file already exists, the function just returns assuming the CA certificate already exists. If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' the resulting CA, and corresponding key, would be written in the following location:: /etc/pki/koji/koji_ca_cert.crt /etc/pki/koji/koji_ca_cert.key CLI Example: .. code-block:: bash salt '*' tls.create_ca test_ca
[ "Create", "a", "Certificate", "Authority", "(", "CA", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L675-L870
train
saltstack/salt
salt/modules/tls.py
get_extensions
def get_extensions(cert_type): ''' Fetch X509 and CSR extension definitions from tls:extensions: (common|server|client) or set them to standard defaults. .. versionadded:: 2015.8.0 cert_type: The type of certificate such as ``server`` or ``client``. CLI Example: .. code-block:: bash salt '*' tls.get_extensions client ''' assert X509_EXT_ENABLED, ('X509 extensions are not supported in ' 'pyOpenSSL prior to version 0.15.1. Your ' 'version: {0}'.format(OpenSSL_version)) ext = {} if cert_type == '': log.error('cert_type set to empty in tls_ca.get_extensions(); ' 'defaulting to ``server``') cert_type = 'server' try: ext['common'] = __salt__['pillar.get']('tls.extensions:common', False) except NameError as err: log.debug(err) if not ext['common'] or ext['common'] == '': ext['common'] = { 'csr': { 'basicConstraints': 'CA:FALSE', }, 'cert': { 'authorityKeyIdentifier': 'keyid,issuer:always', 'subjectKeyIdentifier': 'hash', }, } try: ext['server'] = __salt__['pillar.get']('tls.extensions:server', False) except NameError as err: log.debug(err) if not ext['server'] or ext['server'] == '': ext['server'] = { 'csr': { 'extendedKeyUsage': 'serverAuth', 'keyUsage': 'digitalSignature, keyEncipherment', }, 'cert': {}, } try: ext['client'] = __salt__['pillar.get']('tls.extensions:client', False) except NameError as err: log.debug(err) if not ext['client'] or ext['client'] == '': ext['client'] = { 'csr': { 'extendedKeyUsage': 'clientAuth', 'keyUsage': 'nonRepudiation, digitalSignature, keyEncipherment', }, 'cert': {}, } # possible user-defined profile or a typo if cert_type not in ext: try: ext[cert_type] = __salt__['pillar.get']( 'tls.extensions:{0}'.format(cert_type)) except NameError as e: log.debug( 'pillar, tls:extensions:%s not available or ' 'not operating in a salt context\n%s', cert_type, e ) retval = ext['common'] for Use in retval: retval[Use].update(ext[cert_type][Use]) return retval
python
def get_extensions(cert_type): ''' Fetch X509 and CSR extension definitions from tls:extensions: (common|server|client) or set them to standard defaults. .. versionadded:: 2015.8.0 cert_type: The type of certificate such as ``server`` or ``client``. CLI Example: .. code-block:: bash salt '*' tls.get_extensions client ''' assert X509_EXT_ENABLED, ('X509 extensions are not supported in ' 'pyOpenSSL prior to version 0.15.1. Your ' 'version: {0}'.format(OpenSSL_version)) ext = {} if cert_type == '': log.error('cert_type set to empty in tls_ca.get_extensions(); ' 'defaulting to ``server``') cert_type = 'server' try: ext['common'] = __salt__['pillar.get']('tls.extensions:common', False) except NameError as err: log.debug(err) if not ext['common'] or ext['common'] == '': ext['common'] = { 'csr': { 'basicConstraints': 'CA:FALSE', }, 'cert': { 'authorityKeyIdentifier': 'keyid,issuer:always', 'subjectKeyIdentifier': 'hash', }, } try: ext['server'] = __salt__['pillar.get']('tls.extensions:server', False) except NameError as err: log.debug(err) if not ext['server'] or ext['server'] == '': ext['server'] = { 'csr': { 'extendedKeyUsage': 'serverAuth', 'keyUsage': 'digitalSignature, keyEncipherment', }, 'cert': {}, } try: ext['client'] = __salt__['pillar.get']('tls.extensions:client', False) except NameError as err: log.debug(err) if not ext['client'] or ext['client'] == '': ext['client'] = { 'csr': { 'extendedKeyUsage': 'clientAuth', 'keyUsage': 'nonRepudiation, digitalSignature, keyEncipherment', }, 'cert': {}, } # possible user-defined profile or a typo if cert_type not in ext: try: ext[cert_type] = __salt__['pillar.get']( 'tls.extensions:{0}'.format(cert_type)) except NameError as e: log.debug( 'pillar, tls:extensions:%s not available or ' 'not operating in a salt context\n%s', cert_type, e ) retval = ext['common'] for Use in retval: retval[Use].update(ext[cert_type][Use]) return retval
[ "def", "get_extensions", "(", "cert_type", ")", ":", "assert", "X509_EXT_ENABLED", ",", "(", "'X509 extensions are not supported in '", "'pyOpenSSL prior to version 0.15.1. Your '", "'version: {0}'", ".", "format", "(", "OpenSSL_version", ")", ")", "ext", "=", "{", "}", ...
Fetch X509 and CSR extension definitions from tls:extensions: (common|server|client) or set them to standard defaults. .. versionadded:: 2015.8.0 cert_type: The type of certificate such as ``server`` or ``client``. CLI Example: .. code-block:: bash salt '*' tls.get_extensions client
[ "Fetch", "X509", "and", "CSR", "extension", "definitions", "from", "tls", ":", "extensions", ":", "(", "common|server|client", ")", "or", "set", "them", "to", "standard", "defaults", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L873-L961
train
saltstack/salt
salt/modules/tls.py
create_csr
def create_csr(ca_name, bits=2048, CN='localhost', C='US', ST='Utah', L='Salt Lake City', O='SaltStack', OU=None, emailAddress=None, subjectAltName=None, cacert_path=None, ca_filename=None, csr_path=None, csr_filename=None, digest='sha256', type_ext=False, cert_type='server', replace=False): ''' Create a Certificate Signing Request (CSR) for a particular Certificate Authority (CA) ca_name name of the CA bits number of RSA key bits, default is 2048 CN common name in the request, default is "localhost" C country, default is "US" ST state, default is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" NOTE: Must the same as CA certificate or an error will be raised OU organizational unit, default is None emailAddress email address for the request, default is None subjectAltName valid subjectAltNames in full form, e.g. to add DNS entry you would call this function with this value: examples: ['DNS:somednsname.com', 'DNS:1.2.3.4', 'IP:1.2.3.4', 'IP:2001:4801:7821:77:be76:4eff:fe11:e51', 'email:me@i.like.pie.com'] .. note:: some libraries do not properly query IP: prefixes, instead looking for the given req. source with a DNS: prefix. To be thorough, you may want to include both DNS: and IP: entries if you are using subjectAltNames for destinations for your TLS connections. e.g.: requests to https://1.2.3.4 will fail from python's requests library w/out the second entry in the above list .. versionadded:: 2015.8.0 cert_type Specify the general certificate type. Can be either `server` or `client`. Indicates the set of common extensions added to the CSR. .. code-block:: cfg server: { 'basicConstraints': 'CA:FALSE', 'extendedKeyUsage': 'serverAuth', 'keyUsage': 'digitalSignature, keyEncipherment' } client: { 'basicConstraints': 'CA:FALSE', 'extendedKeyUsage': 'clientAuth', 'keyUsage': 'nonRepudiation, digitalSignature, keyEncipherment' } type_ext boolean. Whether or not to extend the filename with CN_[cert_type] This can be useful if a server and client certificate are needed for the same CN. Defaults to False to avoid introducing an unexpected file naming pattern The files normally named some_subject_CN.csr and some_subject_CN.key will then be saved replace Replace this signing request even if it exists .. versionadded:: 2015.5.1 Writes out a Certificate Signing Request (CSR) If the file already exists, the function just returns assuming the CSR already exists. If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting CSR, and corresponding key, would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.csr /etc/pki/koji/certs/test.egavas.org.key CLI Example: .. code-block:: bash salt '*' tls.create_csr test ''' set_ca_path(cacert_path) if not ca_filename: ca_filename = '{0}_ca_cert'.format(ca_name) if not ca_exists(ca_name, ca_filename=ca_filename): return ('Certificate for CA named "{0}" does not exist, please create ' 'it first.').format(ca_name) if not csr_path: csr_path = '{0}/{1}/certs/'.format(cert_base_path(), ca_name) if not os.path.exists(csr_path): os.makedirs(csr_path) CN_ext = '_{0}'.format(cert_type) if type_ext else '' if not csr_filename: csr_filename = '{0}{1}'.format(CN, CN_ext) csr_f = '{0}/{1}.csr'.format(csr_path, csr_filename) if not replace and os.path.exists(csr_f): return 'Certificate Request "{0}" already exists'.format(csr_f) key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, bits) req = OpenSSL.crypto.X509Req() req.get_subject().C = C req.get_subject().ST = ST req.get_subject().L = L req.get_subject().O = O if OU: req.get_subject().OU = OU req.get_subject().CN = CN if emailAddress: req.get_subject().emailAddress = emailAddress try: extensions = get_extensions(cert_type)['csr'] extension_adds = [] for ext, value in extensions.items(): if isinstance(value, six.string_types): value = salt.utils.stringutils.to_bytes(value) extension_adds.append( OpenSSL.crypto.X509Extension( salt.utils.stringutils.to_bytes(ext), False, value ) ) except AssertionError as err: log.error(err) extensions = [] if subjectAltName: if X509_EXT_ENABLED: if isinstance(subjectAltName, six.string_types): subjectAltName = [subjectAltName] extension_adds.append( OpenSSL.crypto.X509Extension( b'subjectAltName', False, b', '.join(salt.utils.data.encode(subjectAltName)) ) ) else: raise ValueError('subjectAltName cannot be set as X509 ' 'extensions are not supported in pyOpenSSL ' 'prior to version 0.15.1. Your ' 'version: {0}.'.format(OpenSSL_version)) if X509_EXT_ENABLED: req.add_extensions(extension_adds) req.set_pubkey(key) req.sign(key, salt.utils.stringutils.to_str(digest)) # Write private key and request with salt.utils.files.fopen('{0}/{1}.key'.format(csr_path, csr_filename), 'wb+') as priv_key: priv_key.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) ) ) with salt.utils.files.fopen(csr_f, 'wb+') as csr: csr.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_certificate_request( OpenSSL.crypto.FILETYPE_PEM, req ) ) ) ret = 'Created Private Key: "{0}{1}.key." '.format( csr_path, csr_filename ) ret += 'Created CSR for "{0}": "{1}{2}.csr."'.format( CN, csr_path, csr_filename ) return ret
python
def create_csr(ca_name, bits=2048, CN='localhost', C='US', ST='Utah', L='Salt Lake City', O='SaltStack', OU=None, emailAddress=None, subjectAltName=None, cacert_path=None, ca_filename=None, csr_path=None, csr_filename=None, digest='sha256', type_ext=False, cert_type='server', replace=False): ''' Create a Certificate Signing Request (CSR) for a particular Certificate Authority (CA) ca_name name of the CA bits number of RSA key bits, default is 2048 CN common name in the request, default is "localhost" C country, default is "US" ST state, default is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" NOTE: Must the same as CA certificate or an error will be raised OU organizational unit, default is None emailAddress email address for the request, default is None subjectAltName valid subjectAltNames in full form, e.g. to add DNS entry you would call this function with this value: examples: ['DNS:somednsname.com', 'DNS:1.2.3.4', 'IP:1.2.3.4', 'IP:2001:4801:7821:77:be76:4eff:fe11:e51', 'email:me@i.like.pie.com'] .. note:: some libraries do not properly query IP: prefixes, instead looking for the given req. source with a DNS: prefix. To be thorough, you may want to include both DNS: and IP: entries if you are using subjectAltNames for destinations for your TLS connections. e.g.: requests to https://1.2.3.4 will fail from python's requests library w/out the second entry in the above list .. versionadded:: 2015.8.0 cert_type Specify the general certificate type. Can be either `server` or `client`. Indicates the set of common extensions added to the CSR. .. code-block:: cfg server: { 'basicConstraints': 'CA:FALSE', 'extendedKeyUsage': 'serverAuth', 'keyUsage': 'digitalSignature, keyEncipherment' } client: { 'basicConstraints': 'CA:FALSE', 'extendedKeyUsage': 'clientAuth', 'keyUsage': 'nonRepudiation, digitalSignature, keyEncipherment' } type_ext boolean. Whether or not to extend the filename with CN_[cert_type] This can be useful if a server and client certificate are needed for the same CN. Defaults to False to avoid introducing an unexpected file naming pattern The files normally named some_subject_CN.csr and some_subject_CN.key will then be saved replace Replace this signing request even if it exists .. versionadded:: 2015.5.1 Writes out a Certificate Signing Request (CSR) If the file already exists, the function just returns assuming the CSR already exists. If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting CSR, and corresponding key, would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.csr /etc/pki/koji/certs/test.egavas.org.key CLI Example: .. code-block:: bash salt '*' tls.create_csr test ''' set_ca_path(cacert_path) if not ca_filename: ca_filename = '{0}_ca_cert'.format(ca_name) if not ca_exists(ca_name, ca_filename=ca_filename): return ('Certificate for CA named "{0}" does not exist, please create ' 'it first.').format(ca_name) if not csr_path: csr_path = '{0}/{1}/certs/'.format(cert_base_path(), ca_name) if not os.path.exists(csr_path): os.makedirs(csr_path) CN_ext = '_{0}'.format(cert_type) if type_ext else '' if not csr_filename: csr_filename = '{0}{1}'.format(CN, CN_ext) csr_f = '{0}/{1}.csr'.format(csr_path, csr_filename) if not replace and os.path.exists(csr_f): return 'Certificate Request "{0}" already exists'.format(csr_f) key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, bits) req = OpenSSL.crypto.X509Req() req.get_subject().C = C req.get_subject().ST = ST req.get_subject().L = L req.get_subject().O = O if OU: req.get_subject().OU = OU req.get_subject().CN = CN if emailAddress: req.get_subject().emailAddress = emailAddress try: extensions = get_extensions(cert_type)['csr'] extension_adds = [] for ext, value in extensions.items(): if isinstance(value, six.string_types): value = salt.utils.stringutils.to_bytes(value) extension_adds.append( OpenSSL.crypto.X509Extension( salt.utils.stringutils.to_bytes(ext), False, value ) ) except AssertionError as err: log.error(err) extensions = [] if subjectAltName: if X509_EXT_ENABLED: if isinstance(subjectAltName, six.string_types): subjectAltName = [subjectAltName] extension_adds.append( OpenSSL.crypto.X509Extension( b'subjectAltName', False, b', '.join(salt.utils.data.encode(subjectAltName)) ) ) else: raise ValueError('subjectAltName cannot be set as X509 ' 'extensions are not supported in pyOpenSSL ' 'prior to version 0.15.1. Your ' 'version: {0}.'.format(OpenSSL_version)) if X509_EXT_ENABLED: req.add_extensions(extension_adds) req.set_pubkey(key) req.sign(key, salt.utils.stringutils.to_str(digest)) # Write private key and request with salt.utils.files.fopen('{0}/{1}.key'.format(csr_path, csr_filename), 'wb+') as priv_key: priv_key.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) ) ) with salt.utils.files.fopen(csr_f, 'wb+') as csr: csr.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_certificate_request( OpenSSL.crypto.FILETYPE_PEM, req ) ) ) ret = 'Created Private Key: "{0}{1}.key." '.format( csr_path, csr_filename ) ret += 'Created CSR for "{0}": "{1}{2}.csr."'.format( CN, csr_path, csr_filename ) return ret
[ "def", "create_csr", "(", "ca_name", ",", "bits", "=", "2048", ",", "CN", "=", "'localhost'", ",", "C", "=", "'US'", ",", "ST", "=", "'Utah'", ",", "L", "=", "'Salt Lake City'", ",", "O", "=", "'SaltStack'", ",", "OU", "=", "None", ",", "emailAddress...
Create a Certificate Signing Request (CSR) for a particular Certificate Authority (CA) ca_name name of the CA bits number of RSA key bits, default is 2048 CN common name in the request, default is "localhost" C country, default is "US" ST state, default is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" NOTE: Must the same as CA certificate or an error will be raised OU organizational unit, default is None emailAddress email address for the request, default is None subjectAltName valid subjectAltNames in full form, e.g. to add DNS entry you would call this function with this value: examples: ['DNS:somednsname.com', 'DNS:1.2.3.4', 'IP:1.2.3.4', 'IP:2001:4801:7821:77:be76:4eff:fe11:e51', 'email:me@i.like.pie.com'] .. note:: some libraries do not properly query IP: prefixes, instead looking for the given req. source with a DNS: prefix. To be thorough, you may want to include both DNS: and IP: entries if you are using subjectAltNames for destinations for your TLS connections. e.g.: requests to https://1.2.3.4 will fail from python's requests library w/out the second entry in the above list .. versionadded:: 2015.8.0 cert_type Specify the general certificate type. Can be either `server` or `client`. Indicates the set of common extensions added to the CSR. .. code-block:: cfg server: { 'basicConstraints': 'CA:FALSE', 'extendedKeyUsage': 'serverAuth', 'keyUsage': 'digitalSignature, keyEncipherment' } client: { 'basicConstraints': 'CA:FALSE', 'extendedKeyUsage': 'clientAuth', 'keyUsage': 'nonRepudiation, digitalSignature, keyEncipherment' } type_ext boolean. Whether or not to extend the filename with CN_[cert_type] This can be useful if a server and client certificate are needed for the same CN. Defaults to False to avoid introducing an unexpected file naming pattern The files normally named some_subject_CN.csr and some_subject_CN.key will then be saved replace Replace this signing request even if it exists .. versionadded:: 2015.5.1 Writes out a Certificate Signing Request (CSR) If the file already exists, the function just returns assuming the CSR already exists. If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting CSR, and corresponding key, would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.csr /etc/pki/koji/certs/test.egavas.org.key CLI Example: .. code-block:: bash salt '*' tls.create_csr test
[ "Create", "a", "Certificate", "Signing", "Request", "(", "CSR", ")", "for", "a", "particular", "Certificate", "Authority", "(", "CA", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L964-L1193
train
saltstack/salt
salt/modules/tls.py
create_self_signed_cert
def create_self_signed_cert(tls_dir='tls', bits=2048, days=365, CN='localhost', C='US', ST='Utah', L='Salt Lake City', O='SaltStack', OU=None, emailAddress=None, cacert_path=None, cert_filename=None, digest='sha256', replace=False): ''' Create a Self-Signed Certificate (CERT) tls_dir location appended to the ca.cert_base_path, default is 'tls' bits number of RSA key bits, default is 2048 CN common name in the request, default is "localhost" C country, default is "US" ST state, default is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" NOTE: Must the same as CA certificate or an error will be raised OU organizational unit, default is None emailAddress email address for the request, default is None cacert_path absolute path to ca certificates root directory digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 Writes out a Self-Signed Certificate (CERT). If the file already exists, the function just returns. If the following values were set:: ca.cert_base_path='/etc/pki' tls_dir='koji' CN='test.egavas.org' the resulting CERT, and corresponding key, would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.crt /etc/pki/koji/certs/test.egavas.org.key CLI Example: .. code-block:: bash salt '*' tls.create_self_signed_cert Passing options from the command line: .. code-block:: bash salt 'minion' tls.create_self_signed_cert CN='test.mysite.org' ''' set_ca_path(cacert_path) if not os.path.exists('{0}/{1}/certs/'.format(cert_base_path(), tls_dir)): os.makedirs("{0}/{1}/certs/".format(cert_base_path(), tls_dir)) if not cert_filename: cert_filename = CN if not replace and os.path.exists( '{0}/{1}/certs/{2}.crt'.format(cert_base_path(), tls_dir, cert_filename) ): return 'Certificate "{0}" already exists'.format(cert_filename) key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, bits) # create certificate cert = OpenSSL.crypto.X509() cert.set_version(2) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(int(days) * 24 * 60 * 60) cert.get_subject().C = C cert.get_subject().ST = ST cert.get_subject().L = L cert.get_subject().O = O if OU: cert.get_subject().OU = OU cert.get_subject().CN = CN if emailAddress: cert.get_subject().emailAddress = emailAddress cert.set_serial_number(_new_serial(tls_dir)) cert.set_issuer(cert.get_subject()) cert.set_pubkey(key) cert.sign(key, salt.utils.stringutils.to_str(digest)) # Write private key and cert priv_key_path = '{0}/{1}/certs/{2}.key'.format(cert_base_path(), tls_dir, cert_filename) with salt.utils.files.fopen(priv_key_path, 'wb+') as priv_key: priv_key.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) ) ) crt_path = '{0}/{1}/certs/{2}.crt'.format(cert_base_path(), tls_dir, cert_filename) with salt.utils.files.fopen(crt_path, 'wb+') as crt: crt.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_PEM, cert ) ) ) _write_cert_to_database(tls_dir, cert) ret = 'Created Private Key: "{0}/{1}/certs/{2}.key." '.format( cert_base_path(), tls_dir, cert_filename ) ret += 'Created Certificate: "{0}/{1}/certs/{2}.crt."'.format( cert_base_path(), tls_dir, cert_filename ) return ret
python
def create_self_signed_cert(tls_dir='tls', bits=2048, days=365, CN='localhost', C='US', ST='Utah', L='Salt Lake City', O='SaltStack', OU=None, emailAddress=None, cacert_path=None, cert_filename=None, digest='sha256', replace=False): ''' Create a Self-Signed Certificate (CERT) tls_dir location appended to the ca.cert_base_path, default is 'tls' bits number of RSA key bits, default is 2048 CN common name in the request, default is "localhost" C country, default is "US" ST state, default is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" NOTE: Must the same as CA certificate or an error will be raised OU organizational unit, default is None emailAddress email address for the request, default is None cacert_path absolute path to ca certificates root directory digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 Writes out a Self-Signed Certificate (CERT). If the file already exists, the function just returns. If the following values were set:: ca.cert_base_path='/etc/pki' tls_dir='koji' CN='test.egavas.org' the resulting CERT, and corresponding key, would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.crt /etc/pki/koji/certs/test.egavas.org.key CLI Example: .. code-block:: bash salt '*' tls.create_self_signed_cert Passing options from the command line: .. code-block:: bash salt 'minion' tls.create_self_signed_cert CN='test.mysite.org' ''' set_ca_path(cacert_path) if not os.path.exists('{0}/{1}/certs/'.format(cert_base_path(), tls_dir)): os.makedirs("{0}/{1}/certs/".format(cert_base_path(), tls_dir)) if not cert_filename: cert_filename = CN if not replace and os.path.exists( '{0}/{1}/certs/{2}.crt'.format(cert_base_path(), tls_dir, cert_filename) ): return 'Certificate "{0}" already exists'.format(cert_filename) key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, bits) # create certificate cert = OpenSSL.crypto.X509() cert.set_version(2) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(int(days) * 24 * 60 * 60) cert.get_subject().C = C cert.get_subject().ST = ST cert.get_subject().L = L cert.get_subject().O = O if OU: cert.get_subject().OU = OU cert.get_subject().CN = CN if emailAddress: cert.get_subject().emailAddress = emailAddress cert.set_serial_number(_new_serial(tls_dir)) cert.set_issuer(cert.get_subject()) cert.set_pubkey(key) cert.sign(key, salt.utils.stringutils.to_str(digest)) # Write private key and cert priv_key_path = '{0}/{1}/certs/{2}.key'.format(cert_base_path(), tls_dir, cert_filename) with salt.utils.files.fopen(priv_key_path, 'wb+') as priv_key: priv_key.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key) ) ) crt_path = '{0}/{1}/certs/{2}.crt'.format(cert_base_path(), tls_dir, cert_filename) with salt.utils.files.fopen(crt_path, 'wb+') as crt: crt.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_PEM, cert ) ) ) _write_cert_to_database(tls_dir, cert) ret = 'Created Private Key: "{0}/{1}/certs/{2}.key." '.format( cert_base_path(), tls_dir, cert_filename ) ret += 'Created Certificate: "{0}/{1}/certs/{2}.crt."'.format( cert_base_path(), tls_dir, cert_filename ) return ret
[ "def", "create_self_signed_cert", "(", "tls_dir", "=", "'tls'", ",", "bits", "=", "2048", ",", "days", "=", "365", ",", "CN", "=", "'localhost'", ",", "C", "=", "'US'", ",", "ST", "=", "'Utah'", ",", "L", "=", "'Salt Lake City'", ",", "O", "=", "'Sal...
Create a Self-Signed Certificate (CERT) tls_dir location appended to the ca.cert_base_path, default is 'tls' bits number of RSA key bits, default is 2048 CN common name in the request, default is "localhost" C country, default is "US" ST state, default is "Utah" L locality, default is "Centerville", the city where SaltStack originated O organization, default is "SaltStack" NOTE: Must the same as CA certificate or an error will be raised OU organizational unit, default is None emailAddress email address for the request, default is None cacert_path absolute path to ca certificates root directory digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 Writes out a Self-Signed Certificate (CERT). If the file already exists, the function just returns. If the following values were set:: ca.cert_base_path='/etc/pki' tls_dir='koji' CN='test.egavas.org' the resulting CERT, and corresponding key, would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.crt /etc/pki/koji/certs/test.egavas.org.key CLI Example: .. code-block:: bash salt '*' tls.create_self_signed_cert Passing options from the command line: .. code-block:: bash salt 'minion' tls.create_self_signed_cert CN='test.mysite.org'
[ "Create", "a", "Self", "-", "Signed", "Certificate", "(", "CERT", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L1196-L1348
train
saltstack/salt
salt/modules/tls.py
create_ca_signed_cert
def create_ca_signed_cert(ca_name, CN, days=365, cacert_path=None, ca_filename=None, cert_path=None, cert_filename=None, digest='sha256', cert_type=None, type_ext=False, replace=False): ''' Create a Certificate (CERT) signed by a named Certificate Authority (CA) If the certificate file already exists, the function just returns assuming the CERT already exists. The CN *must* match an existing CSR generated by create_csr. If it does not, this method does nothing. ca_name name of the CA CN common name matching the certificate signing request days number of days certificate is valid, default is 365 (1 year) cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 cert_path full path to the certificates directory cert_filename alternative filename for the certificate, useful when using special characters in the CN. If this option is set it will override the certificate filename output effects of ``cert_type``. ``type_ext`` will be completely overridden. .. versionadded:: 2015.5.3 digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 cert_type string. Either 'server' or 'client' (see create_csr() for details). If create_csr(type_ext=True) this function **must** be called with the same cert_type so it can find the CSR file. .. note:: create_csr() defaults to cert_type='server'; therefore, if it was also called with type_ext, cert_type becomes a required argument for create_ca_signed_cert() type_ext bool. If set True, use ``cert_type`` as an extension to the CN when formatting the filename. e.g.: some_subject_CN_server.crt or some_subject_CN_client.crt This facilitates the context where both types are required for the same subject If ``cert_filename`` is `not None`, setting ``type_ext`` has no effect If the following values were set: .. code-block:: text ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting signed certificate would be written in the following location: .. code-block:: text /etc/pki/koji/certs/test.egavas.org.crt CLI Example: .. code-block:: bash salt '*' tls.create_ca_signed_cert test localhost ''' ret = {} set_ca_path(cacert_path) if not ca_filename: ca_filename = '{0}_ca_cert'.format(ca_name) if not cert_path: cert_path = '{0}/{1}/certs'.format(cert_base_path(), ca_name) if type_ext: if not cert_type: log.error('type_ext = True but cert_type is unset. ' 'Certificate not written.') return ret elif cert_type: CN_ext = '_{0}'.format(cert_type) else: CN_ext = '' csr_filename = '{0}{1}'.format(CN, CN_ext) if not cert_filename: cert_filename = '{0}{1}'.format(CN, CN_ext) if not replace and os.path.exists( os.path.join( os.path.sep.join('{0}/{1}/certs/{2}.crt'.format( cert_base_path(), ca_name, cert_filename).split('/') ) ) ): return 'Certificate "{0}" already exists'.format(cert_filename) try: maybe_fix_ssl_version(ca_name, cacert_path=cacert_path, ca_filename=ca_filename) with salt.utils.files.fopen('{0}/{1}/{2}.crt'.format(cert_base_path(), ca_name, ca_filename)) as fhr: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) with salt.utils.files.fopen('{0}/{1}/{2}.key'.format(cert_base_path(), ca_name, ca_filename)) as fhr: ca_key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) except IOError: ret['retcode'] = 1 ret['comment'] = 'There is no CA named "{0}"'.format(ca_name) return ret try: csr_path = '{0}/{1}.csr'.format(cert_path, csr_filename) with salt.utils.files.fopen(csr_path) as fhr: req = OpenSSL.crypto.load_certificate_request( OpenSSL.crypto.FILETYPE_PEM, fhr.read()) except IOError: ret['retcode'] = 1 ret['comment'] = 'There is no CSR that matches the CN "{0}"'.format( cert_filename) return ret exts = [] try: exts.extend(req.get_extensions()) except AttributeError: try: # see: http://bazaar.launchpad.net/~exarkun/pyopenssl/master/revision/189 # support is there from quite a long time, but without API # so we mimic the newly get_extensions method present in ultra # recent pyopenssl distros log.info('req.get_extensions() not supported in pyOpenSSL versions ' 'prior to 0.15. Processing extensions internally. ' 'Your version: %s', OpenSSL_version) native_exts_obj = OpenSSL._util.lib.X509_REQ_get_extensions( req._req) for i in _range(OpenSSL._util.lib.sk_X509_EXTENSION_num( native_exts_obj)): ext = OpenSSL.crypto.X509Extension.__new__( OpenSSL.crypto.X509Extension) ext._extension = OpenSSL._util.lib.sk_X509_EXTENSION_value( native_exts_obj, i) exts.append(ext) except Exception: log.error('X509 extensions are unsupported in pyOpenSSL ' 'versions prior to 0.14. Upgrade required to ' 'use extensions. Current version: %s', OpenSSL_version) cert = OpenSSL.crypto.X509() cert.set_version(2) cert.set_subject(req.get_subject()) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(int(days) * 24 * 60 * 60) cert.set_serial_number(_new_serial(ca_name)) cert.set_issuer(ca_cert.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.add_extensions(exts) cert.sign(ca_key, salt.utils.stringutils.to_str(digest)) cert_full_path = '{0}/{1}.crt'.format(cert_path, cert_filename) with salt.utils.files.fopen(cert_full_path, 'wb+') as crt: crt.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) ) ) _write_cert_to_database(ca_name, cert) return 'Created Certificate for "{0}": "{1}/{2}.crt"'.format( CN, cert_path, cert_filename )
python
def create_ca_signed_cert(ca_name, CN, days=365, cacert_path=None, ca_filename=None, cert_path=None, cert_filename=None, digest='sha256', cert_type=None, type_ext=False, replace=False): ''' Create a Certificate (CERT) signed by a named Certificate Authority (CA) If the certificate file already exists, the function just returns assuming the CERT already exists. The CN *must* match an existing CSR generated by create_csr. If it does not, this method does nothing. ca_name name of the CA CN common name matching the certificate signing request days number of days certificate is valid, default is 365 (1 year) cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 cert_path full path to the certificates directory cert_filename alternative filename for the certificate, useful when using special characters in the CN. If this option is set it will override the certificate filename output effects of ``cert_type``. ``type_ext`` will be completely overridden. .. versionadded:: 2015.5.3 digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 cert_type string. Either 'server' or 'client' (see create_csr() for details). If create_csr(type_ext=True) this function **must** be called with the same cert_type so it can find the CSR file. .. note:: create_csr() defaults to cert_type='server'; therefore, if it was also called with type_ext, cert_type becomes a required argument for create_ca_signed_cert() type_ext bool. If set True, use ``cert_type`` as an extension to the CN when formatting the filename. e.g.: some_subject_CN_server.crt or some_subject_CN_client.crt This facilitates the context where both types are required for the same subject If ``cert_filename`` is `not None`, setting ``type_ext`` has no effect If the following values were set: .. code-block:: text ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting signed certificate would be written in the following location: .. code-block:: text /etc/pki/koji/certs/test.egavas.org.crt CLI Example: .. code-block:: bash salt '*' tls.create_ca_signed_cert test localhost ''' ret = {} set_ca_path(cacert_path) if not ca_filename: ca_filename = '{0}_ca_cert'.format(ca_name) if not cert_path: cert_path = '{0}/{1}/certs'.format(cert_base_path(), ca_name) if type_ext: if not cert_type: log.error('type_ext = True but cert_type is unset. ' 'Certificate not written.') return ret elif cert_type: CN_ext = '_{0}'.format(cert_type) else: CN_ext = '' csr_filename = '{0}{1}'.format(CN, CN_ext) if not cert_filename: cert_filename = '{0}{1}'.format(CN, CN_ext) if not replace and os.path.exists( os.path.join( os.path.sep.join('{0}/{1}/certs/{2}.crt'.format( cert_base_path(), ca_name, cert_filename).split('/') ) ) ): return 'Certificate "{0}" already exists'.format(cert_filename) try: maybe_fix_ssl_version(ca_name, cacert_path=cacert_path, ca_filename=ca_filename) with salt.utils.files.fopen('{0}/{1}/{2}.crt'.format(cert_base_path(), ca_name, ca_filename)) as fhr: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) with salt.utils.files.fopen('{0}/{1}/{2}.key'.format(cert_base_path(), ca_name, ca_filename)) as fhr: ca_key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) except IOError: ret['retcode'] = 1 ret['comment'] = 'There is no CA named "{0}"'.format(ca_name) return ret try: csr_path = '{0}/{1}.csr'.format(cert_path, csr_filename) with salt.utils.files.fopen(csr_path) as fhr: req = OpenSSL.crypto.load_certificate_request( OpenSSL.crypto.FILETYPE_PEM, fhr.read()) except IOError: ret['retcode'] = 1 ret['comment'] = 'There is no CSR that matches the CN "{0}"'.format( cert_filename) return ret exts = [] try: exts.extend(req.get_extensions()) except AttributeError: try: # see: http://bazaar.launchpad.net/~exarkun/pyopenssl/master/revision/189 # support is there from quite a long time, but without API # so we mimic the newly get_extensions method present in ultra # recent pyopenssl distros log.info('req.get_extensions() not supported in pyOpenSSL versions ' 'prior to 0.15. Processing extensions internally. ' 'Your version: %s', OpenSSL_version) native_exts_obj = OpenSSL._util.lib.X509_REQ_get_extensions( req._req) for i in _range(OpenSSL._util.lib.sk_X509_EXTENSION_num( native_exts_obj)): ext = OpenSSL.crypto.X509Extension.__new__( OpenSSL.crypto.X509Extension) ext._extension = OpenSSL._util.lib.sk_X509_EXTENSION_value( native_exts_obj, i) exts.append(ext) except Exception: log.error('X509 extensions are unsupported in pyOpenSSL ' 'versions prior to 0.14. Upgrade required to ' 'use extensions. Current version: %s', OpenSSL_version) cert = OpenSSL.crypto.X509() cert.set_version(2) cert.set_subject(req.get_subject()) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(int(days) * 24 * 60 * 60) cert.set_serial_number(_new_serial(ca_name)) cert.set_issuer(ca_cert.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.add_extensions(exts) cert.sign(ca_key, salt.utils.stringutils.to_str(digest)) cert_full_path = '{0}/{1}.crt'.format(cert_path, cert_filename) with salt.utils.files.fopen(cert_full_path, 'wb+') as crt: crt.write( salt.utils.stringutils.to_bytes( OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) ) ) _write_cert_to_database(ca_name, cert) return 'Created Certificate for "{0}": "{1}/{2}.crt"'.format( CN, cert_path, cert_filename )
[ "def", "create_ca_signed_cert", "(", "ca_name", ",", "CN", ",", "days", "=", "365", ",", "cacert_path", "=", "None", ",", "ca_filename", "=", "None", ",", "cert_path", "=", "None", ",", "cert_filename", "=", "None", ",", "digest", "=", "'sha256'", ",", "...
Create a Certificate (CERT) signed by a named Certificate Authority (CA) If the certificate file already exists, the function just returns assuming the CERT already exists. The CN *must* match an existing CSR generated by create_csr. If it does not, this method does nothing. ca_name name of the CA CN common name matching the certificate signing request days number of days certificate is valid, default is 365 (1 year) cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 cert_path full path to the certificates directory cert_filename alternative filename for the certificate, useful when using special characters in the CN. If this option is set it will override the certificate filename output effects of ``cert_type``. ``type_ext`` will be completely overridden. .. versionadded:: 2015.5.3 digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 cert_type string. Either 'server' or 'client' (see create_csr() for details). If create_csr(type_ext=True) this function **must** be called with the same cert_type so it can find the CSR file. .. note:: create_csr() defaults to cert_type='server'; therefore, if it was also called with type_ext, cert_type becomes a required argument for create_ca_signed_cert() type_ext bool. If set True, use ``cert_type`` as an extension to the CN when formatting the filename. e.g.: some_subject_CN_server.crt or some_subject_CN_client.crt This facilitates the context where both types are required for the same subject If ``cert_filename`` is `not None`, setting ``type_ext`` has no effect If the following values were set: .. code-block:: text ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting signed certificate would be written in the following location: .. code-block:: text /etc/pki/koji/certs/test.egavas.org.crt CLI Example: .. code-block:: bash salt '*' tls.create_ca_signed_cert test localhost
[ "Create", "a", "Certificate", "(", "CERT", ")", "signed", "by", "a", "named", "Certificate", "Authority", "(", "CA", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L1351-L1579
train
saltstack/salt
salt/modules/tls.py
create_pkcs12
def create_pkcs12(ca_name, CN, passphrase='', cacert_path=None, replace=False): ''' Create a PKCS#12 browser certificate for a particular Certificate (CN) ca_name name of the CA CN common name matching the certificate signing request passphrase used to unlock the PKCS#12 certificate when loaded into the browser cacert_path absolute path to ca certificates root directory replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting signed certificate would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.p12 CLI Example: .. code-block:: bash salt '*' tls.create_pkcs12 test localhost ''' set_ca_path(cacert_path) if not replace and os.path.exists( '{0}/{1}/certs/{2}.p12'.format( cert_base_path(), ca_name, CN) ): return 'Certificate "{0}" already exists'.format(CN) try: with salt.utils.files.fopen( '{0}/{1}/{1}_ca_cert.crt'.format(cert_base_path(), ca_name)) as fhr: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) except IOError: return 'There is no CA named "{0}"'.format(ca_name) try: with salt.utils.files.fopen('{0}/{1}/certs/{2}.crt'.format(cert_base_path(), ca_name, CN)) as fhr: cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) with salt.utils.files.fopen('{0}/{1}/certs/{2}.key'.format(cert_base_path(), ca_name, CN)) as fhr: key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) except IOError: return 'There is no certificate that matches the CN "{0}"'.format(CN) pkcs12 = OpenSSL.crypto.PKCS12() pkcs12.set_certificate(cert) pkcs12.set_ca_certificates([ca_cert]) pkcs12.set_privatekey(key) with salt.utils.files.fopen('{0}/{1}/certs/{2}.p12'.format(cert_base_path(), ca_name, CN), 'wb') as ofile: ofile.write( pkcs12.export( passphrase=salt.utils.stringutils.to_bytes(passphrase) ) ) return ('Created PKCS#12 Certificate for "{0}": ' '"{1}/{2}/certs/{0}.p12"').format( CN, cert_base_path(), ca_name, )
python
def create_pkcs12(ca_name, CN, passphrase='', cacert_path=None, replace=False): ''' Create a PKCS#12 browser certificate for a particular Certificate (CN) ca_name name of the CA CN common name matching the certificate signing request passphrase used to unlock the PKCS#12 certificate when loaded into the browser cacert_path absolute path to ca certificates root directory replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting signed certificate would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.p12 CLI Example: .. code-block:: bash salt '*' tls.create_pkcs12 test localhost ''' set_ca_path(cacert_path) if not replace and os.path.exists( '{0}/{1}/certs/{2}.p12'.format( cert_base_path(), ca_name, CN) ): return 'Certificate "{0}" already exists'.format(CN) try: with salt.utils.files.fopen( '{0}/{1}/{1}_ca_cert.crt'.format(cert_base_path(), ca_name)) as fhr: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) except IOError: return 'There is no CA named "{0}"'.format(ca_name) try: with salt.utils.files.fopen('{0}/{1}/certs/{2}.crt'.format(cert_base_path(), ca_name, CN)) as fhr: cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) with salt.utils.files.fopen('{0}/{1}/certs/{2}.key'.format(cert_base_path(), ca_name, CN)) as fhr: key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) except IOError: return 'There is no certificate that matches the CN "{0}"'.format(CN) pkcs12 = OpenSSL.crypto.PKCS12() pkcs12.set_certificate(cert) pkcs12.set_ca_certificates([ca_cert]) pkcs12.set_privatekey(key) with salt.utils.files.fopen('{0}/{1}/certs/{2}.p12'.format(cert_base_path(), ca_name, CN), 'wb') as ofile: ofile.write( pkcs12.export( passphrase=salt.utils.stringutils.to_bytes(passphrase) ) ) return ('Created PKCS#12 Certificate for "{0}": ' '"{1}/{2}/certs/{0}.p12"').format( CN, cert_base_path(), ca_name, )
[ "def", "create_pkcs12", "(", "ca_name", ",", "CN", ",", "passphrase", "=", "''", ",", "cacert_path", "=", "None", ",", "replace", "=", "False", ")", ":", "set_ca_path", "(", "cacert_path", ")", "if", "not", "replace", "and", "os", ".", "path", ".", "ex...
Create a PKCS#12 browser certificate for a particular Certificate (CN) ca_name name of the CA CN common name matching the certificate signing request passphrase used to unlock the PKCS#12 certificate when loaded into the browser cacert_path absolute path to ca certificates root directory replace Replace this certificate even if it exists .. versionadded:: 2015.5.1 If the following values were set:: ca.cert_base_path='/etc/pki' ca_name='koji' CN='test.egavas.org' the resulting signed certificate would be written in the following location:: /etc/pki/koji/certs/test.egavas.org.p12 CLI Example: .. code-block:: bash salt '*' tls.create_pkcs12 test localhost
[ "Create", "a", "PKCS#12", "browser", "certificate", "for", "a", "particular", "Certificate", "(", "CN", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L1582-L1673
train
saltstack/salt
salt/modules/tls.py
cert_info
def cert_info(cert, digest='sha256'): ''' Return information for a particular certificate cert path to the certifiate PEM file or string .. versionchanged:: 2018.3.4 digest what digest to use for fingerprinting CLI Example: .. code-block:: bash salt '*' tls.cert_info /dir/for/certs/cert.pem ''' # format that OpenSSL returns dates in date_fmt = '%Y%m%d%H%M%SZ' if '-----BEGIN' not in cert: with salt.utils.files.fopen(cert) as cert_file: cert = cert_file.read() cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, cert ) issuer = {} for key, value in cert.get_issuer().get_components(): if isinstance(key, bytes): key = salt.utils.stringutils.to_unicode(key) if isinstance(value, bytes): value = salt.utils.stringutils.to_unicode(value) issuer[key] = value subject = {} for key, value in cert.get_subject().get_components(): if isinstance(key, bytes): key = salt.utils.stringutils.to_unicode(key) if isinstance(value, bytes): value = salt.utils.stringutils.to_unicode(value) subject[key] = value ret = { 'fingerprint': salt.utils.stringutils.to_unicode( cert.digest(salt.utils.stringutils.to_str(digest)) ), 'subject': subject, 'issuer': issuer, 'serial_number': cert.get_serial_number(), 'not_before': calendar.timegm(time.strptime( str(cert.get_notBefore().decode(__salt_system_encoding__)), date_fmt)), 'not_after': calendar.timegm(time.strptime( cert.get_notAfter().decode(__salt_system_encoding__), date_fmt)), } # add additional info if your version of pyOpenSSL supports it if hasattr(cert, 'get_extension_count'): ret['extensions'] = {} for i in _range(cert.get_extension_count()): try: ext = cert.get_extension(i) key = salt.utils.stringutils.to_unicode(ext.get_short_name()) ret['extensions'][key] = str(ext).strip() except AttributeError: continue if 'subjectAltName' in ret.get('extensions', {}): valid_entries = ('DNS', 'IP Address') valid_names = set() for name in str(ret['extensions']['subjectAltName']).split(', '): entry, name = name.split(':', 1) if entry not in valid_entries: log.error('Cert %s has an entry (%s) which does not start ' 'with %s', ret['subject'], name, '/'.join(valid_entries)) else: valid_names.add(name) ret['subject_alt_names'] = list(valid_names) if hasattr(cert, 'get_signature_algorithm'): try: value = cert.get_signature_algorithm() if isinstance(value, bytes): value = salt.utils.stringutils.to_unicode(value) ret['signature_algorithm'] = value except AttributeError: # On py3 at least # AttributeError: cdata 'X509 *' points to an opaque type: cannot read fields pass return ret
python
def cert_info(cert, digest='sha256'): ''' Return information for a particular certificate cert path to the certifiate PEM file or string .. versionchanged:: 2018.3.4 digest what digest to use for fingerprinting CLI Example: .. code-block:: bash salt '*' tls.cert_info /dir/for/certs/cert.pem ''' # format that OpenSSL returns dates in date_fmt = '%Y%m%d%H%M%SZ' if '-----BEGIN' not in cert: with salt.utils.files.fopen(cert) as cert_file: cert = cert_file.read() cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, cert ) issuer = {} for key, value in cert.get_issuer().get_components(): if isinstance(key, bytes): key = salt.utils.stringutils.to_unicode(key) if isinstance(value, bytes): value = salt.utils.stringutils.to_unicode(value) issuer[key] = value subject = {} for key, value in cert.get_subject().get_components(): if isinstance(key, bytes): key = salt.utils.stringutils.to_unicode(key) if isinstance(value, bytes): value = salt.utils.stringutils.to_unicode(value) subject[key] = value ret = { 'fingerprint': salt.utils.stringutils.to_unicode( cert.digest(salt.utils.stringutils.to_str(digest)) ), 'subject': subject, 'issuer': issuer, 'serial_number': cert.get_serial_number(), 'not_before': calendar.timegm(time.strptime( str(cert.get_notBefore().decode(__salt_system_encoding__)), date_fmt)), 'not_after': calendar.timegm(time.strptime( cert.get_notAfter().decode(__salt_system_encoding__), date_fmt)), } # add additional info if your version of pyOpenSSL supports it if hasattr(cert, 'get_extension_count'): ret['extensions'] = {} for i in _range(cert.get_extension_count()): try: ext = cert.get_extension(i) key = salt.utils.stringutils.to_unicode(ext.get_short_name()) ret['extensions'][key] = str(ext).strip() except AttributeError: continue if 'subjectAltName' in ret.get('extensions', {}): valid_entries = ('DNS', 'IP Address') valid_names = set() for name in str(ret['extensions']['subjectAltName']).split(', '): entry, name = name.split(':', 1) if entry not in valid_entries: log.error('Cert %s has an entry (%s) which does not start ' 'with %s', ret['subject'], name, '/'.join(valid_entries)) else: valid_names.add(name) ret['subject_alt_names'] = list(valid_names) if hasattr(cert, 'get_signature_algorithm'): try: value = cert.get_signature_algorithm() if isinstance(value, bytes): value = salt.utils.stringutils.to_unicode(value) ret['signature_algorithm'] = value except AttributeError: # On py3 at least # AttributeError: cdata 'X509 *' points to an opaque type: cannot read fields pass return ret
[ "def", "cert_info", "(", "cert", ",", "digest", "=", "'sha256'", ")", ":", "# format that OpenSSL returns dates in", "date_fmt", "=", "'%Y%m%d%H%M%SZ'", "if", "'-----BEGIN'", "not", "in", "cert", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "...
Return information for a particular certificate cert path to the certifiate PEM file or string .. versionchanged:: 2018.3.4 digest what digest to use for fingerprinting CLI Example: .. code-block:: bash salt '*' tls.cert_info /dir/for/certs/cert.pem
[ "Return", "information", "for", "a", "particular", "certificate" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L1676-L1770
train
saltstack/salt
salt/modules/tls.py
create_empty_crl
def create_empty_crl( ca_name, cacert_path=None, ca_filename=None, crl_file=None, digest='sha256'): ''' Create an empty Certificate Revocation List. .. versionadded:: 2015.8.0 ca_name name of the CA cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 crl_file full path to the CRL file digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' CLI Example: .. code-block:: bash salt '*' tls.create_empty_crl ca_name='koji' \ ca_filename='ca' \ crl_file='/etc/openvpn/team1/crl.pem' ''' set_ca_path(cacert_path) if not ca_filename: ca_filename = '{0}_ca_cert'.format(ca_name) if not crl_file: crl_file = '{0}/{1}/crl.pem'.format( _cert_base_path(), ca_name ) if os.path.exists('{0}'.format(crl_file)): return 'CRL "{0}" already exists'.format(crl_file) try: with salt.utils.files.fopen('{0}/{1}/{2}.crt'.format( cert_base_path(), ca_name, ca_filename)) as fp_: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) with salt.utils.files.fopen('{0}/{1}/{2}.key'.format( cert_base_path(), ca_name, ca_filename)) as fp_: ca_key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) except IOError: return 'There is no CA named "{0}"'.format(ca_name) crl = OpenSSL.crypto.CRL() crl_text = crl.export( ca_cert, ca_key, digest=salt.utils.stringutils.to_bytes(digest), ) with salt.utils.files.fopen(crl_file, 'w') as f: f.write(salt.utils.stringutils.to_str(crl_text)) return 'Created an empty CRL: "{0}"'.format(crl_file)
python
def create_empty_crl( ca_name, cacert_path=None, ca_filename=None, crl_file=None, digest='sha256'): ''' Create an empty Certificate Revocation List. .. versionadded:: 2015.8.0 ca_name name of the CA cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 crl_file full path to the CRL file digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' CLI Example: .. code-block:: bash salt '*' tls.create_empty_crl ca_name='koji' \ ca_filename='ca' \ crl_file='/etc/openvpn/team1/crl.pem' ''' set_ca_path(cacert_path) if not ca_filename: ca_filename = '{0}_ca_cert'.format(ca_name) if not crl_file: crl_file = '{0}/{1}/crl.pem'.format( _cert_base_path(), ca_name ) if os.path.exists('{0}'.format(crl_file)): return 'CRL "{0}" already exists'.format(crl_file) try: with salt.utils.files.fopen('{0}/{1}/{2}.crt'.format( cert_base_path(), ca_name, ca_filename)) as fp_: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) with salt.utils.files.fopen('{0}/{1}/{2}.key'.format( cert_base_path(), ca_name, ca_filename)) as fp_: ca_key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) except IOError: return 'There is no CA named "{0}"'.format(ca_name) crl = OpenSSL.crypto.CRL() crl_text = crl.export( ca_cert, ca_key, digest=salt.utils.stringutils.to_bytes(digest), ) with salt.utils.files.fopen(crl_file, 'w') as f: f.write(salt.utils.stringutils.to_str(crl_text)) return 'Created an empty CRL: "{0}"'.format(crl_file)
[ "def", "create_empty_crl", "(", "ca_name", ",", "cacert_path", "=", "None", ",", "ca_filename", "=", "None", ",", "crl_file", "=", "None", ",", "digest", "=", "'sha256'", ")", ":", "set_ca_path", "(", "cacert_path", ")", "if", "not", "ca_filename", ":", "c...
Create an empty Certificate Revocation List. .. versionadded:: 2015.8.0 ca_name name of the CA cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 crl_file full path to the CRL file digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' CLI Example: .. code-block:: bash salt '*' tls.create_empty_crl ca_name='koji' \ ca_filename='ca' \ crl_file='/etc/openvpn/team1/crl.pem'
[ "Create", "an", "empty", "Certificate", "Revocation", "List", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L1773-L1854
train
saltstack/salt
salt/modules/tls.py
revoke_cert
def revoke_cert( ca_name, CN, cacert_path=None, ca_filename=None, cert_path=None, cert_filename=None, crl_file=None, digest='sha256', ): ''' Revoke a certificate. .. versionadded:: 2015.8.0 ca_name Name of the CA. CN Common name matching the certificate signing request. cacert_path Absolute path to ca certificates root directory. ca_filename Alternative filename for the CA. cert_path Path to the cert file. cert_filename Alternative filename for the certificate, useful when using special characters in the CN. crl_file Full path to the CRL file. digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' CLI Example: .. code-block:: bash salt '*' tls.revoke_cert ca_name='koji' \ ca_filename='ca' \ crl_file='/etc/openvpn/team1/crl.pem' ''' set_ca_path(cacert_path) ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name) if ca_filename is None: ca_filename = '{0}_ca_cert'.format(ca_name) if cert_path is None: cert_path = '{0}/{1}/certs'.format(_cert_base_path(), ca_name) if cert_filename is None: cert_filename = '{0}'.format(CN) try: with salt.utils.files.fopen('{0}/{1}/{2}.crt'.format( cert_base_path(), ca_name, ca_filename)) as fp_: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) with salt.utils.files.fopen('{0}/{1}/{2}.key'.format( cert_base_path(), ca_name, ca_filename)) as fp_: ca_key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) except IOError: return 'There is no CA named "{0}"'.format(ca_name) client_cert = _read_cert('{0}/{1}.crt'.format(cert_path, cert_filename)) if client_cert is None: return 'There is no client certificate named "{0}"'.format(CN) index_file, expire_date, serial_number, subject = _get_basic_info( ca_name, client_cert, ca_dir) index_serial_subject = '{0}\tunknown\t{1}'.format( serial_number, subject) index_v_data = 'V\t{0}\t\t{1}'.format( expire_date, index_serial_subject) index_r_data_pattern = re.compile( r"R\t" + expire_date + r"\t\d{12}Z\t" + re.escape(index_serial_subject)) index_r_data = 'R\t{0}\t{1}\t{2}'.format( expire_date, _four_digit_year_to_two_digit(datetime.utcnow()), index_serial_subject) ret = {} with salt.utils.files.fopen(index_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if index_r_data_pattern.match(line): revoke_date = line.split('\t')[2] try: datetime.strptime(revoke_date, two_digit_year_fmt) return ('"{0}/{1}.crt" was already revoked, ' 'serial number: {2}').format( cert_path, cert_filename, serial_number ) except ValueError: ret['retcode'] = 1 ret['comment'] = ("Revocation date '{0}' does not match" "format '{1}'".format( revoke_date, two_digit_year_fmt)) return ret elif index_serial_subject in line: __salt__['file.replace']( index_file, index_v_data, index_r_data, backup=False) break crl = OpenSSL.crypto.CRL() with salt.utils.files.fopen(index_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('R'): fields = line.split('\t') revoked = OpenSSL.crypto.Revoked() revoked.set_serial(salt.utils.stringutils.to_bytes(fields[3])) revoke_date_2_digit = datetime.strptime(fields[2], two_digit_year_fmt) revoked.set_rev_date(salt.utils.stringutils.to_bytes( revoke_date_2_digit.strftime(four_digit_year_fmt) )) crl.add_revoked(revoked) crl_text = crl.export(ca_cert, ca_key, digest=salt.utils.stringutils.to_bytes(digest)) if crl_file is None: crl_file = '{0}/{1}/crl.pem'.format( _cert_base_path(), ca_name ) if os.path.isdir(crl_file): ret['retcode'] = 1 ret['comment'] = 'crl_file "{0}" is an existing directory'.format( crl_file) return ret with salt.utils.files.fopen(crl_file, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(crl_text)) return ('Revoked Certificate: "{0}/{1}.crt", ' 'serial number: {2}').format( cert_path, cert_filename, serial_number )
python
def revoke_cert( ca_name, CN, cacert_path=None, ca_filename=None, cert_path=None, cert_filename=None, crl_file=None, digest='sha256', ): ''' Revoke a certificate. .. versionadded:: 2015.8.0 ca_name Name of the CA. CN Common name matching the certificate signing request. cacert_path Absolute path to ca certificates root directory. ca_filename Alternative filename for the CA. cert_path Path to the cert file. cert_filename Alternative filename for the certificate, useful when using special characters in the CN. crl_file Full path to the CRL file. digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' CLI Example: .. code-block:: bash salt '*' tls.revoke_cert ca_name='koji' \ ca_filename='ca' \ crl_file='/etc/openvpn/team1/crl.pem' ''' set_ca_path(cacert_path) ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name) if ca_filename is None: ca_filename = '{0}_ca_cert'.format(ca_name) if cert_path is None: cert_path = '{0}/{1}/certs'.format(_cert_base_path(), ca_name) if cert_filename is None: cert_filename = '{0}'.format(CN) try: with salt.utils.files.fopen('{0}/{1}/{2}.crt'.format( cert_base_path(), ca_name, ca_filename)) as fp_: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) with salt.utils.files.fopen('{0}/{1}/{2}.key'.format( cert_base_path(), ca_name, ca_filename)) as fp_: ca_key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) except IOError: return 'There is no CA named "{0}"'.format(ca_name) client_cert = _read_cert('{0}/{1}.crt'.format(cert_path, cert_filename)) if client_cert is None: return 'There is no client certificate named "{0}"'.format(CN) index_file, expire_date, serial_number, subject = _get_basic_info( ca_name, client_cert, ca_dir) index_serial_subject = '{0}\tunknown\t{1}'.format( serial_number, subject) index_v_data = 'V\t{0}\t\t{1}'.format( expire_date, index_serial_subject) index_r_data_pattern = re.compile( r"R\t" + expire_date + r"\t\d{12}Z\t" + re.escape(index_serial_subject)) index_r_data = 'R\t{0}\t{1}\t{2}'.format( expire_date, _four_digit_year_to_two_digit(datetime.utcnow()), index_serial_subject) ret = {} with salt.utils.files.fopen(index_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if index_r_data_pattern.match(line): revoke_date = line.split('\t')[2] try: datetime.strptime(revoke_date, two_digit_year_fmt) return ('"{0}/{1}.crt" was already revoked, ' 'serial number: {2}').format( cert_path, cert_filename, serial_number ) except ValueError: ret['retcode'] = 1 ret['comment'] = ("Revocation date '{0}' does not match" "format '{1}'".format( revoke_date, two_digit_year_fmt)) return ret elif index_serial_subject in line: __salt__['file.replace']( index_file, index_v_data, index_r_data, backup=False) break crl = OpenSSL.crypto.CRL() with salt.utils.files.fopen(index_file) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) if line.startswith('R'): fields = line.split('\t') revoked = OpenSSL.crypto.Revoked() revoked.set_serial(salt.utils.stringutils.to_bytes(fields[3])) revoke_date_2_digit = datetime.strptime(fields[2], two_digit_year_fmt) revoked.set_rev_date(salt.utils.stringutils.to_bytes( revoke_date_2_digit.strftime(four_digit_year_fmt) )) crl.add_revoked(revoked) crl_text = crl.export(ca_cert, ca_key, digest=salt.utils.stringutils.to_bytes(digest)) if crl_file is None: crl_file = '{0}/{1}/crl.pem'.format( _cert_base_path(), ca_name ) if os.path.isdir(crl_file): ret['retcode'] = 1 ret['comment'] = 'crl_file "{0}" is an existing directory'.format( crl_file) return ret with salt.utils.files.fopen(crl_file, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(crl_text)) return ('Revoked Certificate: "{0}/{1}.crt", ' 'serial number: {2}').format( cert_path, cert_filename, serial_number )
[ "def", "revoke_cert", "(", "ca_name", ",", "CN", ",", "cacert_path", "=", "None", ",", "ca_filename", "=", "None", ",", "cert_path", "=", "None", ",", "cert_filename", "=", "None", ",", "crl_file", "=", "None", ",", "digest", "=", "'sha256'", ",", ")", ...
Revoke a certificate. .. versionadded:: 2015.8.0 ca_name Name of the CA. CN Common name matching the certificate signing request. cacert_path Absolute path to ca certificates root directory. ca_filename Alternative filename for the CA. cert_path Path to the cert file. cert_filename Alternative filename for the certificate, useful when using special characters in the CN. crl_file Full path to the CRL file. digest The message digest algorithm. Must be a string describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, "md5" or "sha1". Default: 'sha256' CLI Example: .. code-block:: bash salt '*' tls.revoke_cert ca_name='koji' \ ca_filename='ca' \ crl_file='/etc/openvpn/team1/crl.pem'
[ "Revoke", "a", "certificate", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L1857-L2035
train
saltstack/salt
salt/utils/roster_matcher.py
_convert_range_to_list
def _convert_range_to_list(tgt, range_server): ''' convert a seco.range range into a list target ''' r = seco.range.Range(range_server) try: return r.expand(tgt) except seco.range.RangeException as err: log.error('Range server exception: %s', err) return []
python
def _convert_range_to_list(tgt, range_server): ''' convert a seco.range range into a list target ''' r = seco.range.Range(range_server) try: return r.expand(tgt) except seco.range.RangeException as err: log.error('Range server exception: %s', err) return []
[ "def", "_convert_range_to_list", "(", "tgt", ",", "range_server", ")", ":", "r", "=", "seco", ".", "range", ".", "Range", "(", "range_server", ")", "try", ":", "return", "r", ".", "expand", "(", "tgt", ")", "except", "seco", ".", "range", ".", "RangeEx...
convert a seco.range range into a list target
[ "convert", "a", "seco", ".", "range", "range", "into", "a", "list", "target" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/roster_matcher.py#L133-L142
train
saltstack/salt
salt/utils/roster_matcher.py
RosterMatcher._ret_minions
def _ret_minions(self, filter_): ''' Filter minions by a generic filter. ''' minions = {} for minion in filter_(self.raw): data = self.get_data(minion) if data: minions[minion] = data.copy() return minions
python
def _ret_minions(self, filter_): ''' Filter minions by a generic filter. ''' minions = {} for minion in filter_(self.raw): data = self.get_data(minion) if data: minions[minion] = data.copy() return minions
[ "def", "_ret_minions", "(", "self", ",", "filter_", ")", ":", "minions", "=", "{", "}", "for", "minion", "in", "filter_", "(", "self", ".", "raw", ")", ":", "data", "=", "self", ".", "get_data", "(", "minion", ")", "if", "data", ":", "minions", "["...
Filter minions by a generic filter.
[ "Filter", "minions", "by", "a", "generic", "filter", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/roster_matcher.py#L66-L75
train
saltstack/salt
salt/utils/roster_matcher.py
RosterMatcher.ret_glob_minions
def ret_glob_minions(self): ''' Return minions that match via glob ''' fnfilter = functools.partial(fnmatch.filter, pat=self.tgt) return self._ret_minions(fnfilter)
python
def ret_glob_minions(self): ''' Return minions that match via glob ''' fnfilter = functools.partial(fnmatch.filter, pat=self.tgt) return self._ret_minions(fnfilter)
[ "def", "ret_glob_minions", "(", "self", ")", ":", "fnfilter", "=", "functools", ".", "partial", "(", "fnmatch", ".", "filter", ",", "pat", "=", "self", ".", "tgt", ")", "return", "self", ".", "_ret_minions", "(", "fnfilter", ")" ]
Return minions that match via glob
[ "Return", "minions", "that", "match", "via", "glob" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/roster_matcher.py#L77-L82
train
saltstack/salt
salt/utils/roster_matcher.py
RosterMatcher.ret_pcre_minions
def ret_pcre_minions(self): ''' Return minions that match via pcre ''' tgt = re.compile(self.tgt) refilter = functools.partial(filter, tgt.match) return self._ret_minions(refilter)
python
def ret_pcre_minions(self): ''' Return minions that match via pcre ''' tgt = re.compile(self.tgt) refilter = functools.partial(filter, tgt.match) return self._ret_minions(refilter)
[ "def", "ret_pcre_minions", "(", "self", ")", ":", "tgt", "=", "re", ".", "compile", "(", "self", ".", "tgt", ")", "refilter", "=", "functools", ".", "partial", "(", "filter", ",", "tgt", ".", "match", ")", "return", "self", ".", "_ret_minions", "(", ...
Return minions that match via pcre
[ "Return", "minions", "that", "match", "via", "pcre" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/roster_matcher.py#L84-L90
train
saltstack/salt
salt/utils/roster_matcher.py
RosterMatcher.ret_list_minions
def ret_list_minions(self): ''' Return minions that match via list ''' tgt = _tgt_set(self.tgt) return self._ret_minions(tgt.intersection)
python
def ret_list_minions(self): ''' Return minions that match via list ''' tgt = _tgt_set(self.tgt) return self._ret_minions(tgt.intersection)
[ "def", "ret_list_minions", "(", "self", ")", ":", "tgt", "=", "_tgt_set", "(", "self", ".", "tgt", ")", "return", "self", ".", "_ret_minions", "(", "tgt", ".", "intersection", ")" ]
Return minions that match via list
[ "Return", "minions", "that", "match", "via", "list" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/roster_matcher.py#L92-L97
train
saltstack/salt
salt/utils/roster_matcher.py
RosterMatcher.ret_nodegroup_minions
def ret_nodegroup_minions(self): ''' Return minions which match the special list-only groups defined by ssh_list_nodegroups ''' nodegroup = __opts__.get('ssh_list_nodegroups', {}).get(self.tgt, []) nodegroup = _tgt_set(nodegroup) return self._ret_minions(nodegroup.intersection)
python
def ret_nodegroup_minions(self): ''' Return minions which match the special list-only groups defined by ssh_list_nodegroups ''' nodegroup = __opts__.get('ssh_list_nodegroups', {}).get(self.tgt, []) nodegroup = _tgt_set(nodegroup) return self._ret_minions(nodegroup.intersection)
[ "def", "ret_nodegroup_minions", "(", "self", ")", ":", "nodegroup", "=", "__opts__", ".", "get", "(", "'ssh_list_nodegroups'", ",", "{", "}", ")", ".", "get", "(", "self", ".", "tgt", ",", "[", "]", ")", "nodegroup", "=", "_tgt_set", "(", "nodegroup", ...
Return minions which match the special list-only groups defined by ssh_list_nodegroups
[ "Return", "minions", "which", "match", "the", "special", "list", "-", "only", "groups", "defined", "by", "ssh_list_nodegroups" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/roster_matcher.py#L99-L106
train
saltstack/salt
salt/utils/roster_matcher.py
RosterMatcher.ret_range_minions
def ret_range_minions(self): ''' Return minions that are returned by a range query ''' if HAS_RANGE is False: raise RuntimeError("Python lib 'seco.range' is not available") minions = {} range_hosts = _convert_range_to_list(self.tgt, __opts__['range_server']) return self._ret_minions(range_hosts.__contains__)
python
def ret_range_minions(self): ''' Return minions that are returned by a range query ''' if HAS_RANGE is False: raise RuntimeError("Python lib 'seco.range' is not available") minions = {} range_hosts = _convert_range_to_list(self.tgt, __opts__['range_server']) return self._ret_minions(range_hosts.__contains__)
[ "def", "ret_range_minions", "(", "self", ")", ":", "if", "HAS_RANGE", "is", "False", ":", "raise", "RuntimeError", "(", "\"Python lib 'seco.range' is not available\"", ")", "minions", "=", "{", "}", "range_hosts", "=", "_convert_range_to_list", "(", "self", ".", "...
Return minions that are returned by a range query
[ "Return", "minions", "that", "are", "returned", "by", "a", "range", "query" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/roster_matcher.py#L108-L117
train
saltstack/salt
salt/utils/roster_matcher.py
RosterMatcher.get_data
def get_data(self, minion): ''' Return the configured ip ''' ret = copy.deepcopy(__opts__.get('roster_defaults', {})) if isinstance(self.raw[minion], six.string_types): ret.update({'host': self.raw[minion]}) return ret elif isinstance(self.raw[minion], dict): ret.update(self.raw[minion]) return ret return False
python
def get_data(self, minion): ''' Return the configured ip ''' ret = copy.deepcopy(__opts__.get('roster_defaults', {})) if isinstance(self.raw[minion], six.string_types): ret.update({'host': self.raw[minion]}) return ret elif isinstance(self.raw[minion], dict): ret.update(self.raw[minion]) return ret return False
[ "def", "get_data", "(", "self", ",", "minion", ")", ":", "ret", "=", "copy", ".", "deepcopy", "(", "__opts__", ".", "get", "(", "'roster_defaults'", ",", "{", "}", ")", ")", "if", "isinstance", "(", "self", ".", "raw", "[", "minion", "]", ",", "six...
Return the configured ip
[ "Return", "the", "configured", "ip" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/roster_matcher.py#L119-L130
train
saltstack/salt
salt/output/raw.py
output
def output(data, **kwargs): # pylint: disable=unused-argument ''' Rather basic.... ''' if not isinstance(data, six.string_types): data = six.text_type(data) return salt.utils.stringutils.to_unicode(data)
python
def output(data, **kwargs): # pylint: disable=unused-argument ''' Rather basic.... ''' if not isinstance(data, six.string_types): data = six.text_type(data) return salt.utils.stringutils.to_unicode(data)
[ "def", "output", "(", "data", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "if", "not", "isinstance", "(", "data", ",", "six", ".", "string_types", ")", ":", "data", "=", "six", ".", "text_type", "(", "data", ")", "return", "sa...
Rather basic....
[ "Rather", "basic", "...." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/raw.py#L29-L35
train
saltstack/salt
salt/cloud/clouds/parallels.py
avail_images
def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) items = query(action='template') ret = {} for item in items: ret[item.attrib['name']] = item.attrib return ret
python
def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) items = query(action='template') ret = {} for item in items: ret[item.attrib['name']] = item.attrib return ret
[ "def", "avail_images", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_images function must be called with '", "'-f or --function, or with the --list-images option'", ")", "items", "=", "query", "("...
Return a list of the images that are on the provider
[ "Return", "a", "list", "of", "the", "images", "that", "are", "on", "the", "provider" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L84-L99
train
saltstack/salt
salt/cloud/clouds/parallels.py
list_nodes
def list_nodes(call=None): ''' Return a list of the VMs that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} items = query(action='ve') for item in items: name = item.attrib['name'] node = show_instance(name, call='action') ret[name] = { 'id': node['id'], 'image': node['platform']['template-info']['name'], 'state': node['state'], } if 'private-ip' in node['network']: ret[name]['private_ips'] = [node['network']['private-ip']] if 'public-ip' in node['network']: ret[name]['public_ips'] = [node['network']['public-ip']] return ret
python
def list_nodes(call=None): ''' Return a list of the VMs that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) ret = {} items = query(action='ve') for item in items: name = item.attrib['name'] node = show_instance(name, call='action') ret[name] = { 'id': node['id'], 'image': node['platform']['template-info']['name'], 'state': node['state'], } if 'private-ip' in node['network']: ret[name]['private_ips'] = [node['network']['private-ip']] if 'public-ip' in node['network']: ret[name]['public_ips'] = [node['network']['public-ip']] return ret
[ "def", "list_nodes", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes function must be called with -f or --function.'", ")", "ret", "=", "{", "}", "items", "=", "query", "(", "action", ...
Return a list of the VMs that are on the provider
[ "Return", "a", "list", "of", "the", "VMs", "that", "are", "on", "the", "provider" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L102-L128
train
saltstack/salt
salt/cloud/clouds/parallels.py
create_node
def create_node(vm_): ''' Build and submit the XML to create a node ''' # Start the tree content = ET.Element('ve') # Name of the instance name = ET.SubElement(content, 'name') name.text = vm_['name'] # Description, defaults to name desc = ET.SubElement(content, 'description') desc.text = config.get_cloud_config_value( 'desc', vm_, __opts__, default=vm_['name'], search_global=False ) # How many CPU cores, and how fast they are cpu = ET.SubElement(content, 'cpu') cpu.attrib['number'] = config.get_cloud_config_value( 'cpu_number', vm_, __opts__, default='1', search_global=False ) cpu.attrib['power'] = config.get_cloud_config_value( 'cpu_power', vm_, __opts__, default='1000', search_global=False ) # How many megabytes of RAM ram = ET.SubElement(content, 'ram-size') ram.text = config.get_cloud_config_value( 'ram', vm_, __opts__, default='256', search_global=False ) # Bandwidth available, in kbps bandwidth = ET.SubElement(content, 'bandwidth') bandwidth.text = config.get_cloud_config_value( 'bandwidth', vm_, __opts__, default='100', search_global=False ) # How many public IPs will be assigned to this instance ip_num = ET.SubElement(content, 'no-of-public-ip') ip_num.text = config.get_cloud_config_value( 'ip_num', vm_, __opts__, default='1', search_global=False ) # Size of the instance disk disk = ET.SubElement(content, 've-disk') disk.attrib['local'] = 'true' disk.attrib['size'] = config.get_cloud_config_value( 'disk_size', vm_, __opts__, default='10', search_global=False ) # Attributes for the image vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) image = show_image({'image': vm_image}, call='function') platform = ET.SubElement(content, 'platform') template = ET.SubElement(platform, 'template-info') template.attrib['name'] = vm_image os_info = ET.SubElement(platform, 'os-info') os_info.attrib['technology'] = image[vm_image]['technology'] os_info.attrib['type'] = image[vm_image]['osType'] # Username and password admin = ET.SubElement(content, 'admin') admin.attrib['login'] = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) admin.attrib['password'] = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) data = ET.tostring(content, encoding='UTF-8') __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', data, list(data)), }, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) node = query(action='ve', method='POST', data=data) return node
python
def create_node(vm_): ''' Build and submit the XML to create a node ''' # Start the tree content = ET.Element('ve') # Name of the instance name = ET.SubElement(content, 'name') name.text = vm_['name'] # Description, defaults to name desc = ET.SubElement(content, 'description') desc.text = config.get_cloud_config_value( 'desc', vm_, __opts__, default=vm_['name'], search_global=False ) # How many CPU cores, and how fast they are cpu = ET.SubElement(content, 'cpu') cpu.attrib['number'] = config.get_cloud_config_value( 'cpu_number', vm_, __opts__, default='1', search_global=False ) cpu.attrib['power'] = config.get_cloud_config_value( 'cpu_power', vm_, __opts__, default='1000', search_global=False ) # How many megabytes of RAM ram = ET.SubElement(content, 'ram-size') ram.text = config.get_cloud_config_value( 'ram', vm_, __opts__, default='256', search_global=False ) # Bandwidth available, in kbps bandwidth = ET.SubElement(content, 'bandwidth') bandwidth.text = config.get_cloud_config_value( 'bandwidth', vm_, __opts__, default='100', search_global=False ) # How many public IPs will be assigned to this instance ip_num = ET.SubElement(content, 'no-of-public-ip') ip_num.text = config.get_cloud_config_value( 'ip_num', vm_, __opts__, default='1', search_global=False ) # Size of the instance disk disk = ET.SubElement(content, 've-disk') disk.attrib['local'] = 'true' disk.attrib['size'] = config.get_cloud_config_value( 'disk_size', vm_, __opts__, default='10', search_global=False ) # Attributes for the image vm_image = config.get_cloud_config_value( 'image', vm_, __opts__, search_global=False ) image = show_image({'image': vm_image}, call='function') platform = ET.SubElement(content, 'platform') template = ET.SubElement(platform, 'template-info') template.attrib['name'] = vm_image os_info = ET.SubElement(platform, 'os-info') os_info.attrib['technology'] = image[vm_image]['technology'] os_info.attrib['type'] = image[vm_image]['osType'] # Username and password admin = ET.SubElement(content, 'admin') admin.attrib['login'] = config.get_cloud_config_value( 'ssh_username', vm_, __opts__, default='root' ) admin.attrib['password'] = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False ) data = ET.tostring(content, encoding='UTF-8') __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args={ 'kwargs': __utils__['cloud.filter_event']('requesting', data, list(data)), }, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) node = query(action='ve', method='POST', data=data) return node
[ "def", "create_node", "(", "vm_", ")", ":", "# Start the tree", "content", "=", "ET", ".", "Element", "(", "'ve'", ")", "# Name of the instance", "name", "=", "ET", ".", "SubElement", "(", "content", ",", "'name'", ")", "name", ".", "text", "=", "vm_", "...
Build and submit the XML to create a node
[ "Build", "and", "submit", "the", "XML", "to", "create", "a", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L184-L270
train
saltstack/salt
salt/cloud/clouds/parallels.py
create
def create(vm_): ''' Create a single VM from a data dict ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'parallels', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) try: data = create_node(vm_) except Exception as exc: log.error( 'Error creating %s on PARALLELS\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False name = vm_['name'] if not wait_until(name, 'CREATED'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} start(vm_['name'], call='action') if not wait_until(name, 'STARTED'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} def __query_node_data(vm_name): data = show_instance(vm_name, call='action') if 'public-ip' not in data['network']: # Trigger another iteration return return data try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=5 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=5), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) comps = data['network']['public-ip']['address'].split('/') public_ip = comps[0] vm_['ssh_host'] = public_ip ret = __utils__['cloud.bootstrap'](vm_, __opts__) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return data
python
def create(vm_): ''' Create a single VM from a data dict ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'parallels', vm_['profile'], vm_=vm_) is False: return False except AttributeError: pass __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(vm_['name']), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Cloud VM %s', vm_['name']) try: data = create_node(vm_) except Exception as exc: log.error( 'Error creating %s on PARALLELS\n\n' 'The following exception was thrown when trying to ' 'run the initial deployment: \n%s', vm_['name'], exc, # Show the traceback if the debug logging level is enabled exc_info_on_loglevel=logging.DEBUG ) return False name = vm_['name'] if not wait_until(name, 'CREATED'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} start(vm_['name'], call='action') if not wait_until(name, 'STARTED'): return {'Error': 'Unable to start {0}, command timed out'.format(name)} def __query_node_data(vm_name): data = show_instance(vm_name, call='action') if 'public-ip' not in data['network']: # Trigger another iteration return return data try: data = salt.utils.cloud.wait_for_ip( __query_node_data, update_args=(vm_['name'],), timeout=config.get_cloud_config_value( 'wait_for_ip_timeout', vm_, __opts__, default=5 * 60), interval=config.get_cloud_config_value( 'wait_for_ip_interval', vm_, __opts__, default=5), ) except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc: try: # It might be already up, let's destroy it! destroy(vm_['name']) except SaltCloudSystemExit: pass finally: raise SaltCloudSystemExit(six.text_type(exc)) comps = data['network']['public-ip']['address'].split('/') public_ip = comps[0] vm_['ssh_host'] = public_ip ret = __utils__['cloud.bootstrap'](vm_, __opts__) log.info('Created Cloud VM \'%s\'', vm_['name']) log.debug( '\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(vm_['name']), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return data
[ "def", "create", "(", "vm_", ")", ":", "try", ":", "# Check for required profile parameters before sending any API calls.", "if", "vm_", "[", "'profile'", "]", "and", "config", ".", "is_profile_configured", "(", "__opts__", ",", "__active_provider_name__", "or", "'paral...
Create a single VM from a data dict
[ "Create", "a", "single", "VM", "from", "a", "data", "dict" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L273-L365
train
saltstack/salt
salt/cloud/clouds/parallels.py
query
def query(action=None, command=None, args=None, method='GET', data=None): ''' Make a web call to a Parallels provider ''' path = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) auth_handler = _HTTPBasicAuthHandler() auth_handler.add_password( realm='Parallels Instance Manager', uri=path, user=config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd=config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) ) opener = _build_opener(auth_handler) _install_opener(opener) if action: path += action if command: path += '/{0}'.format(command) if not type(args, dict): args = {} kwargs = {'data': data} if isinstance(data, six.string_types) and '<?xml' in data: kwargs['headers'] = { 'Content-type': 'application/xml', } if args: params = _urlencode(args) req = _Request(url='{0}?{1}'.format(path, params), **kwargs) else: req = _Request(url=path, **kwargs) req.get_method = lambda: method log.debug('%s %s', method, req.get_full_url()) if data: log.debug(data) try: result = _urlopen(req) log.debug('PARALLELS Response Status Code: %s', result.getcode()) if 'content-length' in result.headers: content = result.read() result.close() items = ET.fromstring(content) return items return {} except URLError as exc: log.error('PARALLELS Response Status Code: %s %s', exc.code, exc.msg) root = ET.fromstring(exc.read()) log.error(root) return {'error': root}
python
def query(action=None, command=None, args=None, method='GET', data=None): ''' Make a web call to a Parallels provider ''' path = config.get_cloud_config_value( 'url', get_configured_provider(), __opts__, search_global=False ) auth_handler = _HTTPBasicAuthHandler() auth_handler.add_password( realm='Parallels Instance Manager', uri=path, user=config.get_cloud_config_value( 'user', get_configured_provider(), __opts__, search_global=False ), passwd=config.get_cloud_config_value( 'password', get_configured_provider(), __opts__, search_global=False ) ) opener = _build_opener(auth_handler) _install_opener(opener) if action: path += action if command: path += '/{0}'.format(command) if not type(args, dict): args = {} kwargs = {'data': data} if isinstance(data, six.string_types) and '<?xml' in data: kwargs['headers'] = { 'Content-type': 'application/xml', } if args: params = _urlencode(args) req = _Request(url='{0}?{1}'.format(path, params), **kwargs) else: req = _Request(url=path, **kwargs) req.get_method = lambda: method log.debug('%s %s', method, req.get_full_url()) if data: log.debug(data) try: result = _urlopen(req) log.debug('PARALLELS Response Status Code: %s', result.getcode()) if 'content-length' in result.headers: content = result.read() result.close() items = ET.fromstring(content) return items return {} except URLError as exc: log.error('PARALLELS Response Status Code: %s %s', exc.code, exc.msg) root = ET.fromstring(exc.read()) log.error(root) return {'error': root}
[ "def", "query", "(", "action", "=", "None", ",", "command", "=", "None", ",", "args", "=", "None", ",", "method", "=", "'GET'", ",", "data", "=", "None", ")", ":", "path", "=", "config", ".", "get_cloud_config_value", "(", "'url'", ",", "get_configured...
Make a web call to a Parallels provider
[ "Make", "a", "web", "call", "to", "a", "Parallels", "provider" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L368-L432
train
saltstack/salt
salt/cloud/clouds/parallels.py
show_image
def show_image(kwargs, call=None): ''' Show the details from Parallels concerning an image ''' if call != 'function': raise SaltCloudSystemExit( 'The show_image function must be called with -f or --function.' ) items = query(action='template', command=kwargs['image']) if 'error' in items: return items['error'] ret = {} for item in items: ret.update({item.attrib['name']: item.attrib}) return ret
python
def show_image(kwargs, call=None): ''' Show the details from Parallels concerning an image ''' if call != 'function': raise SaltCloudSystemExit( 'The show_image function must be called with -f or --function.' ) items = query(action='template', command=kwargs['image']) if 'error' in items: return items['error'] ret = {} for item in items: ret.update({item.attrib['name']: item.attrib}) return ret
[ "def", "show_image", "(", "kwargs", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The show_image function must be called with -f or --function.'", ")", "items", "=", "query", "(", "action", "=", "...
Show the details from Parallels concerning an image
[ "Show", "the", "details", "from", "Parallels", "concerning", "an", "image" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L449-L466
train
saltstack/salt
salt/cloud/clouds/parallels.py
show_instance
def show_instance(name, call=None): ''' Show the details from Parallels concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) items = query(action='ve', command=name) ret = {} for item in items: if 'text' in item.__dict__: ret[item.tag] = item.text else: ret[item.tag] = item.attrib if item._children: ret[item.tag] = {} children = item._children for child in children: ret[item.tag][child.tag] = child.attrib __utils__['cloud.cache_node'](ret, __active_provider_name__, __opts__) return ret
python
def show_instance(name, call=None): ''' Show the details from Parallels concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) items = query(action='ve', command=name) ret = {} for item in items: if 'text' in item.__dict__: ret[item.tag] = item.text else: ret[item.tag] = item.attrib if item._children: ret[item.tag] = {} children = item._children for child in children: ret[item.tag][child.tag] = child.attrib __utils__['cloud.cache_node'](ret, __active_provider_name__, __opts__) return ret
[ "def", "show_instance", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The show_instance action must be called with -a or --action.'", ")", "items", "=", "query", "(", "action", "=", "'v...
Show the details from Parallels concerning an instance
[ "Show", "the", "details", "from", "Parallels", "concerning", "an", "instance" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L469-L494
train
saltstack/salt
salt/cloud/clouds/parallels.py
wait_until
def wait_until(name, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = show_instance(name, call='action') while True: if node['state'] == state: return True time.sleep(1) if time.time() - start_time > timeout: return False node = show_instance(name, call='action')
python
def wait_until(name, state, timeout=300): ''' Wait until a specific state has been reached on a node ''' start_time = time.time() node = show_instance(name, call='action') while True: if node['state'] == state: return True time.sleep(1) if time.time() - start_time > timeout: return False node = show_instance(name, call='action')
[ "def", "wait_until", "(", "name", ",", "state", ",", "timeout", "=", "300", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "node", "=", "show_instance", "(", "name", ",", "call", "=", "'action'", ")", "while", "True", ":", "if", "node", ...
Wait until a specific state has been reached on a node
[ "Wait", "until", "a", "specific", "state", "has", "been", "reached", "on", "a", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L497-L509
train
saltstack/salt
salt/cloud/clouds/parallels.py
destroy
def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) node = show_instance(name, call='action') if node['state'] == 'STARTED': stop(name, call='action') if not wait_until(name, 'STOPPED'): return { 'Error': 'Unable to destroy {0}, command timed out'.format( name ) } data = query(action='ve', command=name, method='DELETE') if 'error' in data: return data['error'] __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)}
python
def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) node = show_instance(name, call='action') if node['state'] == 'STARTED': stop(name, call='action') if not wait_until(name, 'STOPPED'): return { 'Error': 'Unable to destroy {0}, command timed out'.format( name ) } data = query(action='ve', command=name, method='DELETE') if 'error' in data: return data['error'] __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) if __opts__.get('update_cachedir', False) is True: __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__) return {'Destroyed': '{0} was destroyed.'.format(name)}
[ "def", "destroy", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The destroy action must be called with -d, --destroy, '", "'-a or --action.'", ")", "__utils__", "[", "'cloud.fire_event'", ...
Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine
[ "Destroy", "a", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L512-L564
train
saltstack/salt
salt/cloud/clouds/parallels.py
start
def start(name, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) data = query(action='ve', command='{0}/start'.format(name), method='PUT') if 'error' in data: return data['error'] return {'Started': '{0} was started.'.format(name)}
python
def start(name, call=None): ''' Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) data = query(action='ve', command='{0}/start'.format(name), method='PUT') if 'error' in data: return data['error'] return {'Started': '{0} was started.'.format(name)}
[ "def", "start", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The show_instance action must be called with -a or --action.'", ")", "data", "=", "query", "(", "action", "=", "'ve'", ",...
Start a node. CLI Example: .. code-block:: bash salt-cloud -a start mymachine
[ "Start", "a", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/parallels.py#L567-L587
train
saltstack/salt
salt/returners/telegram_return.py
returner
def returner(ret): ''' Send a Telegram message with the data. :param ret: The data to be sent. :return: Boolean if message was sent successfully. ''' _options = _get_options(ret) chat_id = _options.get('chat_id') token = _options.get('token') if not chat_id: log.error('telegram.chat_id not defined in salt config') if not token: log.error('telegram.token not defined in salt config') returns = ret.get('return') message = ('id: {0}\r\n' 'function: {1}\r\n' 'function args: {2}\r\n' 'jid: {3}\r\n' 'return: {4}\r\n').format( ret.get('id'), ret.get('fun'), ret.get('fun_args'), ret.get('jid'), returns) return __salt__['telegram.post_message'](message, chat_id=chat_id, token=token)
python
def returner(ret): ''' Send a Telegram message with the data. :param ret: The data to be sent. :return: Boolean if message was sent successfully. ''' _options = _get_options(ret) chat_id = _options.get('chat_id') token = _options.get('token') if not chat_id: log.error('telegram.chat_id not defined in salt config') if not token: log.error('telegram.token not defined in salt config') returns = ret.get('return') message = ('id: {0}\r\n' 'function: {1}\r\n' 'function args: {2}\r\n' 'jid: {3}\r\n' 'return: {4}\r\n').format( ret.get('id'), ret.get('fun'), ret.get('fun_args'), ret.get('jid'), returns) return __salt__['telegram.post_message'](message, chat_id=chat_id, token=token)
[ "def", "returner", "(", "ret", ")", ":", "_options", "=", "_get_options", "(", "ret", ")", "chat_id", "=", "_options", ".", "get", "(", "'chat_id'", ")", "token", "=", "_options", ".", "get", "(", "'token'", ")", "if", "not", "chat_id", ":", "log", "...
Send a Telegram message with the data. :param ret: The data to be sent. :return: Boolean if message was sent successfully.
[ "Send", "a", "Telegram", "message", "with", "the", "data", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/telegram_return.py#L67-L99
train
saltstack/salt
salt/returners/local_cache.py
_walk_through
def _walk_through(job_dir): ''' Walk though the jid dir and look for jobs ''' serial = salt.payload.Serial(__opts__) for top in os.listdir(job_dir): t_path = os.path.join(job_dir, top) if not os.path.exists(t_path): continue for final in os.listdir(t_path): load_path = os.path.join(t_path, final, LOAD_P) if not os.path.isfile(load_path): continue with salt.utils.files.fopen(load_path, 'rb') as rfh: try: job = serial.load(rfh) except Exception: log.exception('Failed to deserialize %s', load_path) continue if not job: log.error('Deserialization of job succeded but there is no data in %s', load_path) continue jid = job['jid'] yield jid, job, t_path, final
python
def _walk_through(job_dir): ''' Walk though the jid dir and look for jobs ''' serial = salt.payload.Serial(__opts__) for top in os.listdir(job_dir): t_path = os.path.join(job_dir, top) if not os.path.exists(t_path): continue for final in os.listdir(t_path): load_path = os.path.join(t_path, final, LOAD_P) if not os.path.isfile(load_path): continue with salt.utils.files.fopen(load_path, 'rb') as rfh: try: job = serial.load(rfh) except Exception: log.exception('Failed to deserialize %s', load_path) continue if not job: log.error('Deserialization of job succeded but there is no data in %s', load_path) continue jid = job['jid'] yield jid, job, t_path, final
[ "def", "_walk_through", "(", "job_dir", ")", ":", "serial", "=", "salt", ".", "payload", ".", "Serial", "(", "__opts__", ")", "for", "top", "in", "os", ".", "listdir", "(", "job_dir", ")", ":", "t_path", "=", "os", ".", "path", ".", "join", "(", "j...
Walk though the jid dir and look for jobs
[ "Walk", "though", "the", "jid", "dir", "and", "look", "for", "jobs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L56-L84
train
saltstack/salt
salt/returners/local_cache.py
prep_jid
def prep_jid(nocache=False, passed_jid=None, recurse_count=0): ''' Return a job id and prepare the job id directory. This is the function responsible for making sure jids don't collide (unless it is passed a jid). So do what you have to do to make sure that stays the case ''' if recurse_count >= 5: err = 'prep_jid could not store a jid after {0} tries.'.format(recurse_count) log.error(err) raise salt.exceptions.SaltCacheError(err) if passed_jid is None: # this can be a None or an empty string. jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) # Make sure we create the jid dir, otherwise someone else is using it, # meaning we need a new jid. if not os.path.isdir(jid_dir): try: os.makedirs(jid_dir) except OSError: time.sleep(0.1) if passed_jid is None: return prep_jid(nocache=nocache, recurse_count=recurse_count+1) try: with salt.utils.files.fopen(os.path.join(jid_dir, 'jid'), 'wb+') as fn_: fn_.write(salt.utils.stringutils.to_bytes(jid)) if nocache: with salt.utils.files.fopen(os.path.join(jid_dir, 'nocache'), 'wb+'): pass except IOError: log.warning( 'Could not write out jid file for job %s. Retrying.', jid) time.sleep(0.1) return prep_jid(passed_jid=jid, nocache=nocache, recurse_count=recurse_count+1) return jid
python
def prep_jid(nocache=False, passed_jid=None, recurse_count=0): ''' Return a job id and prepare the job id directory. This is the function responsible for making sure jids don't collide (unless it is passed a jid). So do what you have to do to make sure that stays the case ''' if recurse_count >= 5: err = 'prep_jid could not store a jid after {0} tries.'.format(recurse_count) log.error(err) raise salt.exceptions.SaltCacheError(err) if passed_jid is None: # this can be a None or an empty string. jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) # Make sure we create the jid dir, otherwise someone else is using it, # meaning we need a new jid. if not os.path.isdir(jid_dir): try: os.makedirs(jid_dir) except OSError: time.sleep(0.1) if passed_jid is None: return prep_jid(nocache=nocache, recurse_count=recurse_count+1) try: with salt.utils.files.fopen(os.path.join(jid_dir, 'jid'), 'wb+') as fn_: fn_.write(salt.utils.stringutils.to_bytes(jid)) if nocache: with salt.utils.files.fopen(os.path.join(jid_dir, 'nocache'), 'wb+'): pass except IOError: log.warning( 'Could not write out jid file for job %s. Retrying.', jid) time.sleep(0.1) return prep_jid(passed_jid=jid, nocache=nocache, recurse_count=recurse_count+1) return jid
[ "def", "prep_jid", "(", "nocache", "=", "False", ",", "passed_jid", "=", "None", ",", "recurse_count", "=", "0", ")", ":", "if", "recurse_count", ">=", "5", ":", "err", "=", "'prep_jid could not store a jid after {0} tries.'", ".", "format", "(", "recurse_count"...
Return a job id and prepare the job id directory. This is the function responsible for making sure jids don't collide (unless it is passed a jid). So do what you have to do to make sure that stays the case
[ "Return", "a", "job", "id", "and", "prepare", "the", "job", "id", "directory", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L88-L130
train
saltstack/salt
salt/returners/local_cache.py
returner
def returner(load): ''' Return data to the local job cache ''' serial = salt.payload.Serial(__opts__) # if a minion is returning a standalone job, get a jobid if load['jid'] == 'req': load['jid'] = prep_jid(nocache=load.get('nocache', False)) jid_dir = salt.utils.jid.jid_dir(load['jid'], _job_dir(), __opts__['hash_type']) if os.path.exists(os.path.join(jid_dir, 'nocache')): return hn_dir = os.path.join(jid_dir, load['id']) try: os.makedirs(hn_dir) except OSError as err: if err.errno == errno.EEXIST: # Minion has already returned this jid and it should be dropped log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False elif err.errno == errno.ENOENT: log.error( 'An inconsistency occurred, a job was received with a job id ' '(%s) that is not present in the local cache', load['jid'] ) return False raise serial.dump( dict((key, load[key]) for key in ['return', 'retcode', 'success'] if key in load), # Use atomic open here to avoid the file being read before it's # completely written to. Refs #1935 salt.utils.atomicfile.atomic_open( os.path.join(hn_dir, RETURN_P), 'w+b' ) ) if 'out' in load: serial.dump( load['out'], # Use atomic open here to avoid the file being read before # it's completely written to. Refs #1935 salt.utils.atomicfile.atomic_open( os.path.join(hn_dir, OUT_P), 'w+b' ) )
python
def returner(load): ''' Return data to the local job cache ''' serial = salt.payload.Serial(__opts__) # if a minion is returning a standalone job, get a jobid if load['jid'] == 'req': load['jid'] = prep_jid(nocache=load.get('nocache', False)) jid_dir = salt.utils.jid.jid_dir(load['jid'], _job_dir(), __opts__['hash_type']) if os.path.exists(os.path.join(jid_dir, 'nocache')): return hn_dir = os.path.join(jid_dir, load['id']) try: os.makedirs(hn_dir) except OSError as err: if err.errno == errno.EEXIST: # Minion has already returned this jid and it should be dropped log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False elif err.errno == errno.ENOENT: log.error( 'An inconsistency occurred, a job was received with a job id ' '(%s) that is not present in the local cache', load['jid'] ) return False raise serial.dump( dict((key, load[key]) for key in ['return', 'retcode', 'success'] if key in load), # Use atomic open here to avoid the file being read before it's # completely written to. Refs #1935 salt.utils.atomicfile.atomic_open( os.path.join(hn_dir, RETURN_P), 'w+b' ) ) if 'out' in load: serial.dump( load['out'], # Use atomic open here to avoid the file being read before # it's completely written to. Refs #1935 salt.utils.atomicfile.atomic_open( os.path.join(hn_dir, OUT_P), 'w+b' ) )
[ "def", "returner", "(", "load", ")", ":", "serial", "=", "salt", ".", "payload", ".", "Serial", "(", "__opts__", ")", "# if a minion is returning a standalone job, get a jobid", "if", "load", "[", "'jid'", "]", "==", "'req'", ":", "load", "[", "'jid'", "]", ...
Return data to the local job cache
[ "Return", "data", "to", "the", "local", "job", "cache" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L133-L184
train
saltstack/salt
salt/returners/local_cache.py
save_load
def save_load(jid, clear_load, minions=None, recurse_count=0): ''' Save the load to the specified jid minions argument is to provide a pre-computed list of matched minions for the job, for cases when this function can't compute that list itself (such as for salt-ssh) ''' if recurse_count >= 5: err = ('save_load could not write job cache file after {0} retries.' .format(recurse_count)) log.error(err) raise salt.exceptions.SaltCacheError(err) jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) serial = salt.payload.Serial(__opts__) # Save the invocation information try: if not os.path.exists(jid_dir): os.makedirs(jid_dir) except OSError as exc: if exc.errno == errno.EEXIST: # rarely, the directory can be already concurrently created between # the os.path.exists and the os.makedirs lines above pass else: raise try: with salt.utils.files.fopen(os.path.join(jid_dir, LOAD_P), 'w+b') as wfh: serial.dump(clear_load, wfh) except IOError as exc: log.warning( 'Could not write job invocation cache file: %s', exc ) time.sleep(0.1) return save_load(jid=jid, clear_load=clear_load, recurse_count=recurse_count+1) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': if minions is None: ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] # save the minions to a cache so we can see in the UI save_minions(jid, minions)
python
def save_load(jid, clear_load, minions=None, recurse_count=0): ''' Save the load to the specified jid minions argument is to provide a pre-computed list of matched minions for the job, for cases when this function can't compute that list itself (such as for salt-ssh) ''' if recurse_count >= 5: err = ('save_load could not write job cache file after {0} retries.' .format(recurse_count)) log.error(err) raise salt.exceptions.SaltCacheError(err) jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) serial = salt.payload.Serial(__opts__) # Save the invocation information try: if not os.path.exists(jid_dir): os.makedirs(jid_dir) except OSError as exc: if exc.errno == errno.EEXIST: # rarely, the directory can be already concurrently created between # the os.path.exists and the os.makedirs lines above pass else: raise try: with salt.utils.files.fopen(os.path.join(jid_dir, LOAD_P), 'w+b') as wfh: serial.dump(clear_load, wfh) except IOError as exc: log.warning( 'Could not write job invocation cache file: %s', exc ) time.sleep(0.1) return save_load(jid=jid, clear_load=clear_load, recurse_count=recurse_count+1) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': if minions is None: ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] # save the minions to a cache so we can see in the UI save_minions(jid, minions)
[ "def", "save_load", "(", "jid", ",", "clear_load", ",", "minions", "=", "None", ",", "recurse_count", "=", "0", ")", ":", "if", "recurse_count", ">=", "5", ":", "err", "=", "(", "'save_load could not write job cache file after {0} retries.'", ".", "format", "(",...
Save the load to the specified jid minions argument is to provide a pre-computed list of matched minions for the job, for cases when this function can't compute that list itself (such as for salt-ssh)
[ "Save", "the", "load", "to", "the", "specified", "jid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L187-L238
train
saltstack/salt
salt/returners/local_cache.py
save_minions
def save_minions(jid, minions, syndic_id=None): ''' Save/update the serialized list of minions for a given job ''' # Ensure we have a list for Python 3 compatability minions = list(minions) log.debug( 'Adding minions for job %s%s: %s', jid, ' from syndic master \'{0}\''.format(syndic_id) if syndic_id else '', minions ) serial = salt.payload.Serial(__opts__) jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) try: if not os.path.exists(jid_dir): os.makedirs(jid_dir) except OSError as exc: if exc.errno == errno.EEXIST: # rarely, the directory can be already concurrently created between # the os.path.exists and the os.makedirs lines above pass else: raise if syndic_id is not None: minions_path = os.path.join( jid_dir, SYNDIC_MINIONS_P.format(syndic_id) ) else: minions_path = os.path.join(jid_dir, MINIONS_P) try: if not os.path.exists(jid_dir): try: os.makedirs(jid_dir) except OSError: pass with salt.utils.files.fopen(minions_path, 'w+b') as wfh: serial.dump(minions, wfh) except IOError as exc: log.error( 'Failed to write minion list %s to job cache file %s: %s', minions, minions_path, exc )
python
def save_minions(jid, minions, syndic_id=None): ''' Save/update the serialized list of minions for a given job ''' # Ensure we have a list for Python 3 compatability minions = list(minions) log.debug( 'Adding minions for job %s%s: %s', jid, ' from syndic master \'{0}\''.format(syndic_id) if syndic_id else '', minions ) serial = salt.payload.Serial(__opts__) jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) try: if not os.path.exists(jid_dir): os.makedirs(jid_dir) except OSError as exc: if exc.errno == errno.EEXIST: # rarely, the directory can be already concurrently created between # the os.path.exists and the os.makedirs lines above pass else: raise if syndic_id is not None: minions_path = os.path.join( jid_dir, SYNDIC_MINIONS_P.format(syndic_id) ) else: minions_path = os.path.join(jid_dir, MINIONS_P) try: if not os.path.exists(jid_dir): try: os.makedirs(jid_dir) except OSError: pass with salt.utils.files.fopen(minions_path, 'w+b') as wfh: serial.dump(minions, wfh) except IOError as exc: log.error( 'Failed to write minion list %s to job cache file %s: %s', minions, minions_path, exc )
[ "def", "save_minions", "(", "jid", ",", "minions", ",", "syndic_id", "=", "None", ")", ":", "# Ensure we have a list for Python 3 compatability", "minions", "=", "list", "(", "minions", ")", "log", ".", "debug", "(", "'Adding minions for job %s%s: %s'", ",", "jid", ...
Save/update the serialized list of minions for a given job
[ "Save", "/", "update", "the", "serialized", "list", "of", "minions", "for", "a", "given", "job" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L241-L289
train
saltstack/salt
salt/returners/local_cache.py
get_load
def get_load(jid): ''' Return the load data that marks a specified jid ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) load_fn = os.path.join(jid_dir, LOAD_P) if not os.path.exists(jid_dir) or not os.path.exists(load_fn): return {} serial = salt.payload.Serial(__opts__) ret = {} load_p = os.path.join(jid_dir, LOAD_P) num_tries = 5 for index in range(1, num_tries + 1): with salt.utils.files.fopen(load_p, 'rb') as rfh: try: ret = serial.load(rfh) break except Exception as exc: if index == num_tries: time.sleep(0.25) else: log.critical('Failed to unpack %s', load_p) raise exc if ret is None: ret = {} minions_cache = [os.path.join(jid_dir, MINIONS_P)] minions_cache.extend( glob.glob(os.path.join(jid_dir, SYNDIC_MINIONS_P.format('*'))) ) all_minions = set() for minions_path in minions_cache: log.debug('Reading minion list from %s', minions_path) try: with salt.utils.files.fopen(minions_path, 'rb') as rfh: all_minions.update(serial.load(rfh)) except IOError as exc: salt.utils.files.process_read_exception(exc, minions_path) if all_minions: ret['Minions'] = sorted(all_minions) return ret
python
def get_load(jid): ''' Return the load data that marks a specified jid ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) load_fn = os.path.join(jid_dir, LOAD_P) if not os.path.exists(jid_dir) or not os.path.exists(load_fn): return {} serial = salt.payload.Serial(__opts__) ret = {} load_p = os.path.join(jid_dir, LOAD_P) num_tries = 5 for index in range(1, num_tries + 1): with salt.utils.files.fopen(load_p, 'rb') as rfh: try: ret = serial.load(rfh) break except Exception as exc: if index == num_tries: time.sleep(0.25) else: log.critical('Failed to unpack %s', load_p) raise exc if ret is None: ret = {} minions_cache = [os.path.join(jid_dir, MINIONS_P)] minions_cache.extend( glob.glob(os.path.join(jid_dir, SYNDIC_MINIONS_P.format('*'))) ) all_minions = set() for minions_path in minions_cache: log.debug('Reading minion list from %s', minions_path) try: with salt.utils.files.fopen(minions_path, 'rb') as rfh: all_minions.update(serial.load(rfh)) except IOError as exc: salt.utils.files.process_read_exception(exc, minions_path) if all_minions: ret['Minions'] = sorted(all_minions) return ret
[ "def", "get_load", "(", "jid", ")", ":", "jid_dir", "=", "salt", ".", "utils", ".", "jid", ".", "jid_dir", "(", "jid", ",", "_job_dir", "(", ")", ",", "__opts__", "[", "'hash_type'", "]", ")", "load_fn", "=", "os", ".", "path", ".", "join", "(", ...
Return the load data that marks a specified jid
[ "Return", "the", "load", "data", "that", "marks", "a", "specified", "jid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L292-L333
train
saltstack/salt
salt/returners/local_cache.py
get_jid
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) serial = salt.payload.Serial(__opts__) ret = {} # Check to see if the jid is real, if not return the empty dict if not os.path.isdir(jid_dir): return ret for fn_ in os.listdir(jid_dir): if fn_.startswith('.'): continue if fn_ not in ret: retp = os.path.join(jid_dir, fn_, RETURN_P) outp = os.path.join(jid_dir, fn_, OUT_P) if not os.path.isfile(retp): continue while fn_ not in ret: try: with salt.utils.files.fopen(retp, 'rb') as rfh: ret_data = serial.load(rfh) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which return.p contains the only return data to # the new that is dict containing 'return' and optionally 'retcode' and # 'success'. ret_data = {'return': ret_data} ret[fn_] = ret_data if os.path.isfile(outp): with salt.utils.files.fopen(outp, 'rb') as rfh: ret[fn_]['out'] = serial.load(rfh) except Exception as exc: if 'Permission denied:' in six.text_type(exc): raise return ret
python
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) serial = salt.payload.Serial(__opts__) ret = {} # Check to see if the jid is real, if not return the empty dict if not os.path.isdir(jid_dir): return ret for fn_ in os.listdir(jid_dir): if fn_.startswith('.'): continue if fn_ not in ret: retp = os.path.join(jid_dir, fn_, RETURN_P) outp = os.path.join(jid_dir, fn_, OUT_P) if not os.path.isfile(retp): continue while fn_ not in ret: try: with salt.utils.files.fopen(retp, 'rb') as rfh: ret_data = serial.load(rfh) if not isinstance(ret_data, dict) or 'return' not in ret_data: # Convert the old format in which return.p contains the only return data to # the new that is dict containing 'return' and optionally 'retcode' and # 'success'. ret_data = {'return': ret_data} ret[fn_] = ret_data if os.path.isfile(outp): with salt.utils.files.fopen(outp, 'rb') as rfh: ret[fn_]['out'] = serial.load(rfh) except Exception as exc: if 'Permission denied:' in six.text_type(exc): raise return ret
[ "def", "get_jid", "(", "jid", ")", ":", "jid_dir", "=", "salt", ".", "utils", ".", "jid", ".", "jid_dir", "(", "jid", ",", "_job_dir", "(", ")", ",", "__opts__", "[", "'hash_type'", "]", ")", "serial", "=", "salt", ".", "payload", ".", "Serial", "(...
Return the information returned when the specified job id was executed
[ "Return", "the", "information", "returned", "when", "the", "specified", "job", "id", "was", "executed" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L336-L371
train
saltstack/salt
salt/returners/local_cache.py
get_jids
def get_jids(): ''' Return a dict mapping all job ids to job information ''' ret = {} for jid, job, _, _ in _walk_through(_job_dir()): ret[jid] = salt.utils.jid.format_jid_instance(jid, job) if __opts__.get('job_cache_store_endtime'): endtime = get_endtime(jid) if endtime: ret[jid]['EndTime'] = endtime return ret
python
def get_jids(): ''' Return a dict mapping all job ids to job information ''' ret = {} for jid, job, _, _ in _walk_through(_job_dir()): ret[jid] = salt.utils.jid.format_jid_instance(jid, job) if __opts__.get('job_cache_store_endtime'): endtime = get_endtime(jid) if endtime: ret[jid]['EndTime'] = endtime return ret
[ "def", "get_jids", "(", ")", ":", "ret", "=", "{", "}", "for", "jid", ",", "job", ",", "_", ",", "_", "in", "_walk_through", "(", "_job_dir", "(", ")", ")", ":", "ret", "[", "jid", "]", "=", "salt", ".", "utils", ".", "jid", ".", "format_jid_in...
Return a dict mapping all job ids to job information
[ "Return", "a", "dict", "mapping", "all", "job", "ids", "to", "job", "information" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L374-L387
train
saltstack/salt
salt/returners/local_cache.py
get_jids_filter
def get_jids_filter(count, filter_find_job=True): ''' Return a list of all jobs information filtered by the given criteria. :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs ''' keys = [] ret = [] for jid, job, _, _ in _walk_through(_job_dir()): job = salt.utils.jid.format_jid_instance_ext(jid, job) if filter_find_job and job['Function'] == 'saltutil.find_job': continue i = bisect.bisect(keys, jid) if len(keys) == count and i == 0: continue keys.insert(i, jid) ret.insert(i, job) if len(keys) > count: del keys[0] del ret[0] return ret
python
def get_jids_filter(count, filter_find_job=True): ''' Return a list of all jobs information filtered by the given criteria. :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs ''' keys = [] ret = [] for jid, job, _, _ in _walk_through(_job_dir()): job = salt.utils.jid.format_jid_instance_ext(jid, job) if filter_find_job and job['Function'] == 'saltutil.find_job': continue i = bisect.bisect(keys, jid) if len(keys) == count and i == 0: continue keys.insert(i, jid) ret.insert(i, job) if len(keys) > count: del keys[0] del ret[0] return ret
[ "def", "get_jids_filter", "(", "count", ",", "filter_find_job", "=", "True", ")", ":", "keys", "=", "[", "]", "ret", "=", "[", "]", "for", "jid", ",", "job", ",", "_", ",", "_", "in", "_walk_through", "(", "_job_dir", "(", ")", ")", ":", "job", "...
Return a list of all jobs information filtered by the given criteria. :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs
[ "Return", "a", "list", "of", "all", "jobs", "information", "filtered", "by", "the", "given", "criteria", ".", ":", "param", "int", "count", ":", "show", "not", "more", "than", "the", "count", "of", "most", "recent", "jobs", ":", "param", "bool", "filter_...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L390-L410
train
saltstack/salt
salt/returners/local_cache.py
clean_old_jobs
def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' if __opts__['keep_jobs'] != 0: jid_root = _job_dir() if not os.path.exists(jid_root): return # Keep track of any empty t_path dirs that need to be removed later dirs_to_remove = set() for top in os.listdir(jid_root): t_path = os.path.join(jid_root, top) if not os.path.exists(t_path): continue # Check if there are any stray/empty JID t_path dirs t_path_dirs = os.listdir(t_path) if not t_path_dirs and t_path not in dirs_to_remove: dirs_to_remove.add(t_path) continue for final in t_path_dirs: f_path = os.path.join(t_path, final) jid_file = os.path.join(f_path, 'jid') if not os.path.isfile(jid_file) and os.path.exists(f_path): # No jid file means corrupted cache entry, scrub it # by removing the entire f_path directory shutil.rmtree(f_path) elif os.path.isfile(jid_file): jid_ctime = os.stat(jid_file).st_ctime hours_difference = (time.time() - jid_ctime) / 3600.0 if hours_difference > __opts__['keep_jobs'] and os.path.exists(t_path): # Remove the entire f_path from the original JID dir try: shutil.rmtree(f_path) except OSError as err: log.error('Unable to remove %s: %s', f_path, err) # Remove empty JID dirs from job cache, if they're old enough. # JID dirs may be empty either from a previous cache-clean with the bug # Listed in #29286 still present, or the JID dir was only recently made # And the jid file hasn't been created yet. if dirs_to_remove: for t_path in dirs_to_remove: # Checking the time again prevents a possible race condition where # t_path JID dirs were created, but not yet populated by a jid file. t_path_ctime = os.stat(t_path).st_ctime hours_difference = (time.time() - t_path_ctime) / 3600.0 if hours_difference > __opts__['keep_jobs']: shutil.rmtree(t_path)
python
def clean_old_jobs(): ''' Clean out the old jobs from the job cache ''' if __opts__['keep_jobs'] != 0: jid_root = _job_dir() if not os.path.exists(jid_root): return # Keep track of any empty t_path dirs that need to be removed later dirs_to_remove = set() for top in os.listdir(jid_root): t_path = os.path.join(jid_root, top) if not os.path.exists(t_path): continue # Check if there are any stray/empty JID t_path dirs t_path_dirs = os.listdir(t_path) if not t_path_dirs and t_path not in dirs_to_remove: dirs_to_remove.add(t_path) continue for final in t_path_dirs: f_path = os.path.join(t_path, final) jid_file = os.path.join(f_path, 'jid') if not os.path.isfile(jid_file) and os.path.exists(f_path): # No jid file means corrupted cache entry, scrub it # by removing the entire f_path directory shutil.rmtree(f_path) elif os.path.isfile(jid_file): jid_ctime = os.stat(jid_file).st_ctime hours_difference = (time.time() - jid_ctime) / 3600.0 if hours_difference > __opts__['keep_jobs'] and os.path.exists(t_path): # Remove the entire f_path from the original JID dir try: shutil.rmtree(f_path) except OSError as err: log.error('Unable to remove %s: %s', f_path, err) # Remove empty JID dirs from job cache, if they're old enough. # JID dirs may be empty either from a previous cache-clean with the bug # Listed in #29286 still present, or the JID dir was only recently made # And the jid file hasn't been created yet. if dirs_to_remove: for t_path in dirs_to_remove: # Checking the time again prevents a possible race condition where # t_path JID dirs were created, but not yet populated by a jid file. t_path_ctime = os.stat(t_path).st_ctime hours_difference = (time.time() - t_path_ctime) / 3600.0 if hours_difference > __opts__['keep_jobs']: shutil.rmtree(t_path)
[ "def", "clean_old_jobs", "(", ")", ":", "if", "__opts__", "[", "'keep_jobs'", "]", "!=", "0", ":", "jid_root", "=", "_job_dir", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "jid_root", ")", ":", "return", "# Keep track of any empty t_path ...
Clean out the old jobs from the job cache
[ "Clean", "out", "the", "old", "jobs", "from", "the", "job", "cache" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L413-L466
train
saltstack/salt
salt/returners/local_cache.py
update_endtime
def update_endtime(jid, time): ''' Update (or store) the end time for a given job Endtime is stored as a plain text string ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) try: if not os.path.exists(jid_dir): os.makedirs(jid_dir) with salt.utils.files.fopen(os.path.join(jid_dir, ENDTIME), 'w') as etfile: etfile.write(salt.utils.stringutils.to_str(time)) except IOError as exc: log.warning('Could not write job invocation cache file: %s', exc)
python
def update_endtime(jid, time): ''' Update (or store) the end time for a given job Endtime is stored as a plain text string ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) try: if not os.path.exists(jid_dir): os.makedirs(jid_dir) with salt.utils.files.fopen(os.path.join(jid_dir, ENDTIME), 'w') as etfile: etfile.write(salt.utils.stringutils.to_str(time)) except IOError as exc: log.warning('Could not write job invocation cache file: %s', exc)
[ "def", "update_endtime", "(", "jid", ",", "time", ")", ":", "jid_dir", "=", "salt", ".", "utils", ".", "jid", ".", "jid_dir", "(", "jid", ",", "_job_dir", "(", ")", ",", "__opts__", "[", "'hash_type'", "]", ")", "try", ":", "if", "not", "os", ".", ...
Update (or store) the end time for a given job Endtime is stored as a plain text string
[ "Update", "(", "or", "store", ")", "the", "end", "time", "for", "a", "given", "job" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L469-L482
train
saltstack/salt
salt/returners/local_cache.py
get_endtime
def get_endtime(jid): ''' Retrieve the stored endtime for a given job Returns False if no endtime is present ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) etpath = os.path.join(jid_dir, ENDTIME) if not os.path.exists(etpath): return False with salt.utils.files.fopen(etpath, 'r') as etfile: endtime = salt.utils.stringutils.to_unicode(etfile.read()).strip('\n') return endtime
python
def get_endtime(jid): ''' Retrieve the stored endtime for a given job Returns False if no endtime is present ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) etpath = os.path.join(jid_dir, ENDTIME) if not os.path.exists(etpath): return False with salt.utils.files.fopen(etpath, 'r') as etfile: endtime = salt.utils.stringutils.to_unicode(etfile.read()).strip('\n') return endtime
[ "def", "get_endtime", "(", "jid", ")", ":", "jid_dir", "=", "salt", ".", "utils", ".", "jid", ".", "jid_dir", "(", "jid", ",", "_job_dir", "(", ")", ",", "__opts__", "[", "'hash_type'", "]", ")", "etpath", "=", "os", ".", "path", ".", "join", "(", ...
Retrieve the stored endtime for a given job Returns False if no endtime is present
[ "Retrieve", "the", "stored", "endtime", "for", "a", "given", "job" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L485-L497
train
saltstack/salt
salt/returners/local_cache.py
save_reg
def save_reg(data): ''' Save the register to msgpack files ''' reg_dir = _reg_dir() regfile = os.path.join(reg_dir, 'register') try: if not os.path.exists(reg_dir): os.makedirs(reg_dir) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise try: with salt.utils.files.fopen(regfile, 'a') as fh_: salt.utils.msgpack.dump(data, fh_) except Exception: log.error('Could not write to msgpack file %s', __opts__['outdir']) raise
python
def save_reg(data): ''' Save the register to msgpack files ''' reg_dir = _reg_dir() regfile = os.path.join(reg_dir, 'register') try: if not os.path.exists(reg_dir): os.makedirs(reg_dir) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise try: with salt.utils.files.fopen(regfile, 'a') as fh_: salt.utils.msgpack.dump(data, fh_) except Exception: log.error('Could not write to msgpack file %s', __opts__['outdir']) raise
[ "def", "save_reg", "(", "data", ")", ":", "reg_dir", "=", "_reg_dir", "(", ")", "regfile", "=", "os", ".", "path", ".", "join", "(", "reg_dir", ",", "'register'", ")", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "reg_dir", ")", ...
Save the register to msgpack files
[ "Save", "the", "register", "to", "msgpack", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L507-L526
train
saltstack/salt
salt/returners/local_cache.py
load_reg
def load_reg(): ''' Load the register from msgpack files ''' reg_dir = _reg_dir() regfile = os.path.join(reg_dir, 'register') try: with salt.utils.files.fopen(regfile, 'r') as fh_: return salt.utils.msgpack.load(fh_) except Exception: log.error('Could not write to msgpack file %s', __opts__['outdir']) raise
python
def load_reg(): ''' Load the register from msgpack files ''' reg_dir = _reg_dir() regfile = os.path.join(reg_dir, 'register') try: with salt.utils.files.fopen(regfile, 'r') as fh_: return salt.utils.msgpack.load(fh_) except Exception: log.error('Could not write to msgpack file %s', __opts__['outdir']) raise
[ "def", "load_reg", "(", ")", ":", "reg_dir", "=", "_reg_dir", "(", ")", "regfile", "=", "os", ".", "path", ".", "join", "(", "reg_dir", ",", "'register'", ")", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "regfile", ",...
Load the register from msgpack files
[ "Load", "the", "register", "from", "msgpack", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L529-L540
train
saltstack/salt
salt/serializers/yamlex.py
merge_recursive
def merge_recursive(obj_a, obj_b, level=False): ''' Merge obj_b into obj_a. ''' return aggregate(obj_a, obj_b, level, map_class=AggregatedMap, sequence_class=AggregatedSequence)
python
def merge_recursive(obj_a, obj_b, level=False): ''' Merge obj_b into obj_a. ''' return aggregate(obj_a, obj_b, level, map_class=AggregatedMap, sequence_class=AggregatedSequence)
[ "def", "merge_recursive", "(", "obj_a", ",", "obj_b", ",", "level", "=", "False", ")", ":", "return", "aggregate", "(", "obj_a", ",", "obj_b", ",", "level", ",", "map_class", "=", "AggregatedMap", ",", "sequence_class", "=", "AggregatedSequence", ")" ]
Merge obj_b into obj_a.
[ "Merge", "obj_b", "into", "obj_a", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/yamlex.py#L427-L433
train
saltstack/salt
salt/serializers/yamlex.py
Loader.construct_yaml_omap
def construct_yaml_omap(self, node): ''' Build the SLSMap ''' sls_map = SLSMap() if not isinstance(node, MappingNode): raise ConstructorError( None, None, 'expected a mapping node, but found {0}'.format(node.id), node.start_mark) self.flatten_mapping(node) for key_node, value_node in node.value: # !reset instruction applies on document only. # It tells to reset previous decoded value for this present key. reset = key_node.tag == '!reset' # even if !aggregate tag apply only to values and not keys # it's a reason to act as a such nazi. if key_node.tag == '!aggregate': log.warning('!aggregate applies on values only, not on keys') value_node.tag = key_node.tag key_node.tag = self.resolve_sls_tag(key_node)[0] key = self.construct_object(key_node, deep=False) try: hash(key) except TypeError: err = ('While constructing a mapping {0} found unacceptable ' 'key {1}').format(node.start_mark, key_node.start_mark) raise ConstructorError(err) value = self.construct_object(value_node, deep=False) if key in sls_map and not reset: value = merge_recursive(sls_map[key], value) sls_map[key] = value return sls_map
python
def construct_yaml_omap(self, node): ''' Build the SLSMap ''' sls_map = SLSMap() if not isinstance(node, MappingNode): raise ConstructorError( None, None, 'expected a mapping node, but found {0}'.format(node.id), node.start_mark) self.flatten_mapping(node) for key_node, value_node in node.value: # !reset instruction applies on document only. # It tells to reset previous decoded value for this present key. reset = key_node.tag == '!reset' # even if !aggregate tag apply only to values and not keys # it's a reason to act as a such nazi. if key_node.tag == '!aggregate': log.warning('!aggregate applies on values only, not on keys') value_node.tag = key_node.tag key_node.tag = self.resolve_sls_tag(key_node)[0] key = self.construct_object(key_node, deep=False) try: hash(key) except TypeError: err = ('While constructing a mapping {0} found unacceptable ' 'key {1}').format(node.start_mark, key_node.start_mark) raise ConstructorError(err) value = self.construct_object(value_node, deep=False) if key in sls_map and not reset: value = merge_recursive(sls_map[key], value) sls_map[key] = value return sls_map
[ "def", "construct_yaml_omap", "(", "self", ",", "node", ")", ":", "sls_map", "=", "SLSMap", "(", ")", "if", "not", "isinstance", "(", "node", ",", "MappingNode", ")", ":", "raise", "ConstructorError", "(", "None", ",", "None", ",", "'expected a mapping node,...
Build the SLSMap
[ "Build", "the", "SLSMap" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/yamlex.py#L214-L252
train
saltstack/salt
salt/serializers/yamlex.py
Loader.construct_sls_str
def construct_sls_str(self, node): ''' Build the SLSString. ''' # Ensure obj is str, not py2 unicode or py3 bytes obj = self.construct_scalar(node) if six.PY2: obj = obj.encode('utf-8') return SLSString(obj)
python
def construct_sls_str(self, node): ''' Build the SLSString. ''' # Ensure obj is str, not py2 unicode or py3 bytes obj = self.construct_scalar(node) if six.PY2: obj = obj.encode('utf-8') return SLSString(obj)
[ "def", "construct_sls_str", "(", "self", ",", "node", ")", ":", "# Ensure obj is str, not py2 unicode or py3 bytes", "obj", "=", "self", ".", "construct_scalar", "(", "node", ")", "if", "six", ".", "PY2", ":", "obj", "=", "obj", ".", "encode", "(", "'utf-8'", ...
Build the SLSString.
[ "Build", "the", "SLSString", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/yamlex.py#L254-L263
train
saltstack/salt
salt/serializers/yamlex.py
Loader.construct_sls_int
def construct_sls_int(self, node): ''' Verify integers and pass them in correctly is they are declared as octal ''' if node.value == '0': pass elif node.value.startswith('0') \ and not node.value.startswith(('0b', '0x')): node.value = node.value.lstrip('0') # If value was all zeros, node.value would have been reduced to # an empty string. Change it to '0'. if node.value == '': node.value = '0' return int(node.value)
python
def construct_sls_int(self, node): ''' Verify integers and pass them in correctly is they are declared as octal ''' if node.value == '0': pass elif node.value.startswith('0') \ and not node.value.startswith(('0b', '0x')): node.value = node.value.lstrip('0') # If value was all zeros, node.value would have been reduced to # an empty string. Change it to '0'. if node.value == '': node.value = '0' return int(node.value)
[ "def", "construct_sls_int", "(", "self", ",", "node", ")", ":", "if", "node", ".", "value", "==", "'0'", ":", "pass", "elif", "node", ".", "value", ".", "startswith", "(", "'0'", ")", "and", "not", "node", ".", "value", ".", "startswith", "(", "(", ...
Verify integers and pass them in correctly is they are declared as octal
[ "Verify", "integers", "and", "pass", "them", "in", "correctly", "is", "they", "are", "declared", "as", "octal" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/yamlex.py#L265-L279
train
saltstack/salt
salt/states/boto_dynamodb.py
present
def present(name=None, table_name=None, region=None, key=None, keyid=None, profile=None, read_capacity_units=None, write_capacity_units=None, alarms=None, alarms_from_pillar="boto_dynamodb_alarms", hash_key=None, hash_key_data_type=None, range_key=None, range_key_data_type=None, local_indexes=None, global_indexes=None, backup_configs_from_pillars='boto_dynamodb_backup_configs'): ''' Ensure the DynamoDB table exists. Table throughput can be updated after table creation. Global secondary indexes (GSIs) are managed with some exceptions: - If a GSI deletion is detected, a failure will occur (deletes should be done manually in the AWS console). - If multiple GSIs are added in a single Salt call, a failure will occur (boto supports one creation at a time). Note that this only applies after table creation; multiple GSIs can be created during table creation. - Updates to existing GSIs are limited to read/write capacity only (DynamoDB limitation). name Name of the DynamoDB table table_name Name of the DynamoDB table (deprecated) region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. read_capacity_units The read throughput for this table write_capacity_units The write throughput for this table hash_key The name of the attribute that will be used as the hash key for this table hash_key_data_type The DynamoDB datatype of the hash key range_key The name of the attribute that will be used as the range key for this table range_key_data_type The DynamoDB datatype of the range key local_indexes The local indexes you would like to create global_indexes The global indexes you would like to create backup_configs_from_pillars Pillars to use to configure DataPipeline backups ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if table_name: ret['warnings'] = ['boto_dynamodb.present: `table_name` is deprecated.' ' Please use `name` instead.'] ret['name'] = table_name name = table_name comments = [] changes_old = {} changes_new = {} # Ensure DynamoDB table exists table_exists = __salt__['boto_dynamodb.exists']( name, region, key, keyid, profile ) if not table_exists: if __opts__['test']: ret['result'] = None ret['comment'] = 'DynamoDB table {0} would be created.'.format(name) return ret else: is_created = __salt__['boto_dynamodb.create_table']( name, region, key, keyid, profile, read_capacity_units, write_capacity_units, hash_key, hash_key_data_type, range_key, range_key_data_type, local_indexes, global_indexes ) if not is_created: ret['result'] = False ret['comment'] = 'Failed to create table {0}'.format(name) _add_changes(ret, changes_old, changes_new) return ret comments.append('DynamoDB table {0} was successfully created'.format(name)) changes_new['table'] = name changes_new['read_capacity_units'] = read_capacity_units changes_new['write_capacity_units'] = write_capacity_units changes_new['hash_key'] = hash_key changes_new['hash_key_data_type'] = hash_key_data_type changes_new['range_key'] = range_key changes_new['range_key_data_type'] = range_key_data_type changes_new['local_indexes'] = local_indexes changes_new['global_indexes'] = global_indexes else: comments.append('DynamoDB table {0} exists'.format(name)) # Ensure DynamoDB table provisioned throughput matches description = __salt__['boto_dynamodb.describe']( name, region, key, keyid, profile ) provisioned_throughput = description.get('Table', {}).get('ProvisionedThroughput', {}) current_write_capacity_units = provisioned_throughput.get('WriteCapacityUnits') current_read_capacity_units = provisioned_throughput.get('ReadCapacityUnits') throughput_matches = (current_write_capacity_units == write_capacity_units and current_read_capacity_units == read_capacity_units) if not throughput_matches: if __opts__['test']: ret['result'] = None comments.append('DynamoDB table {0} is set to be updated.'.format(name)) else: is_updated = __salt__['boto_dynamodb.update']( name, throughput={ 'read': read_capacity_units, 'write': write_capacity_units, }, region=region, key=key, keyid=keyid, profile=profile, ) if not is_updated: ret['result'] = False ret['comment'] = 'Failed to update table {0}'.format(name) _add_changes(ret, changes_old, changes_new) return ret comments.append('DynamoDB table {0} was successfully updated'.format(name)) changes_old['read_capacity_units'] = current_read_capacity_units, changes_old['write_capacity_units'] = current_write_capacity_units, changes_new['read_capacity_units'] = read_capacity_units, changes_new['write_capacity_units'] = write_capacity_units, else: comments.append('DynamoDB table {0} throughput matches'.format(name)) provisioned_indexes = description.get('Table', {}).get('GlobalSecondaryIndexes', []) _ret = _global_indexes_present(provisioned_indexes, global_indexes, changes_old, changes_new, comments, name, region, key, keyid, profile) if not _ret['result']: comments.append(_ret['comment']) ret['result'] = _ret['result'] if ret['result'] is False: ret['comment'] = ',\n'.join(comments) _add_changes(ret, changes_old, changes_new) return ret _ret = _alarms_present(name, alarms, alarms_from_pillar, write_capacity_units, read_capacity_units, region, key, keyid, profile) ret['changes'] = dictupdate.update(ret['changes'], _ret['changes']) comments.append(_ret['comment']) if not _ret['result']: ret['result'] = _ret['result'] if ret['result'] is False: ret['comment'] = ',\n'.join(comments) _add_changes(ret, changes_old, changes_new) return ret # Ensure backup datapipeline is present datapipeline_configs = copy.deepcopy( __salt__['pillar.get'](backup_configs_from_pillars, []) ) for config in datapipeline_configs: datapipeline_ret = _ensure_backup_datapipeline_present( name=name, schedule_name=config['name'], period=config['period'], utc_hour=config['utc_hour'], s3_base_location=config['s3_base_location'], ) # Add comments and changes if successful changes were made (True for live mode, # None for test mode). if datapipeline_ret['result'] in [True, None]: ret['result'] = datapipeline_ret['result'] comments.append(datapipeline_ret['comment']) if datapipeline_ret.get('changes'): ret['changes']['backup_datapipeline_{0}'.format(config['name'])] = \ datapipeline_ret.get('changes'), else: ret['comment'] = ',\n'.join([ret['comment'], datapipeline_ret['comment']]) _add_changes(ret, changes_old, changes_new) return ret ret['comment'] = ',\n'.join(comments) _add_changes(ret, changes_old, changes_new) return ret
python
def present(name=None, table_name=None, region=None, key=None, keyid=None, profile=None, read_capacity_units=None, write_capacity_units=None, alarms=None, alarms_from_pillar="boto_dynamodb_alarms", hash_key=None, hash_key_data_type=None, range_key=None, range_key_data_type=None, local_indexes=None, global_indexes=None, backup_configs_from_pillars='boto_dynamodb_backup_configs'): ''' Ensure the DynamoDB table exists. Table throughput can be updated after table creation. Global secondary indexes (GSIs) are managed with some exceptions: - If a GSI deletion is detected, a failure will occur (deletes should be done manually in the AWS console). - If multiple GSIs are added in a single Salt call, a failure will occur (boto supports one creation at a time). Note that this only applies after table creation; multiple GSIs can be created during table creation. - Updates to existing GSIs are limited to read/write capacity only (DynamoDB limitation). name Name of the DynamoDB table table_name Name of the DynamoDB table (deprecated) region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. read_capacity_units The read throughput for this table write_capacity_units The write throughput for this table hash_key The name of the attribute that will be used as the hash key for this table hash_key_data_type The DynamoDB datatype of the hash key range_key The name of the attribute that will be used as the range key for this table range_key_data_type The DynamoDB datatype of the range key local_indexes The local indexes you would like to create global_indexes The global indexes you would like to create backup_configs_from_pillars Pillars to use to configure DataPipeline backups ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if table_name: ret['warnings'] = ['boto_dynamodb.present: `table_name` is deprecated.' ' Please use `name` instead.'] ret['name'] = table_name name = table_name comments = [] changes_old = {} changes_new = {} # Ensure DynamoDB table exists table_exists = __salt__['boto_dynamodb.exists']( name, region, key, keyid, profile ) if not table_exists: if __opts__['test']: ret['result'] = None ret['comment'] = 'DynamoDB table {0} would be created.'.format(name) return ret else: is_created = __salt__['boto_dynamodb.create_table']( name, region, key, keyid, profile, read_capacity_units, write_capacity_units, hash_key, hash_key_data_type, range_key, range_key_data_type, local_indexes, global_indexes ) if not is_created: ret['result'] = False ret['comment'] = 'Failed to create table {0}'.format(name) _add_changes(ret, changes_old, changes_new) return ret comments.append('DynamoDB table {0} was successfully created'.format(name)) changes_new['table'] = name changes_new['read_capacity_units'] = read_capacity_units changes_new['write_capacity_units'] = write_capacity_units changes_new['hash_key'] = hash_key changes_new['hash_key_data_type'] = hash_key_data_type changes_new['range_key'] = range_key changes_new['range_key_data_type'] = range_key_data_type changes_new['local_indexes'] = local_indexes changes_new['global_indexes'] = global_indexes else: comments.append('DynamoDB table {0} exists'.format(name)) # Ensure DynamoDB table provisioned throughput matches description = __salt__['boto_dynamodb.describe']( name, region, key, keyid, profile ) provisioned_throughput = description.get('Table', {}).get('ProvisionedThroughput', {}) current_write_capacity_units = provisioned_throughput.get('WriteCapacityUnits') current_read_capacity_units = provisioned_throughput.get('ReadCapacityUnits') throughput_matches = (current_write_capacity_units == write_capacity_units and current_read_capacity_units == read_capacity_units) if not throughput_matches: if __opts__['test']: ret['result'] = None comments.append('DynamoDB table {0} is set to be updated.'.format(name)) else: is_updated = __salt__['boto_dynamodb.update']( name, throughput={ 'read': read_capacity_units, 'write': write_capacity_units, }, region=region, key=key, keyid=keyid, profile=profile, ) if not is_updated: ret['result'] = False ret['comment'] = 'Failed to update table {0}'.format(name) _add_changes(ret, changes_old, changes_new) return ret comments.append('DynamoDB table {0} was successfully updated'.format(name)) changes_old['read_capacity_units'] = current_read_capacity_units, changes_old['write_capacity_units'] = current_write_capacity_units, changes_new['read_capacity_units'] = read_capacity_units, changes_new['write_capacity_units'] = write_capacity_units, else: comments.append('DynamoDB table {0} throughput matches'.format(name)) provisioned_indexes = description.get('Table', {}).get('GlobalSecondaryIndexes', []) _ret = _global_indexes_present(provisioned_indexes, global_indexes, changes_old, changes_new, comments, name, region, key, keyid, profile) if not _ret['result']: comments.append(_ret['comment']) ret['result'] = _ret['result'] if ret['result'] is False: ret['comment'] = ',\n'.join(comments) _add_changes(ret, changes_old, changes_new) return ret _ret = _alarms_present(name, alarms, alarms_from_pillar, write_capacity_units, read_capacity_units, region, key, keyid, profile) ret['changes'] = dictupdate.update(ret['changes'], _ret['changes']) comments.append(_ret['comment']) if not _ret['result']: ret['result'] = _ret['result'] if ret['result'] is False: ret['comment'] = ',\n'.join(comments) _add_changes(ret, changes_old, changes_new) return ret # Ensure backup datapipeline is present datapipeline_configs = copy.deepcopy( __salt__['pillar.get'](backup_configs_from_pillars, []) ) for config in datapipeline_configs: datapipeline_ret = _ensure_backup_datapipeline_present( name=name, schedule_name=config['name'], period=config['period'], utc_hour=config['utc_hour'], s3_base_location=config['s3_base_location'], ) # Add comments and changes if successful changes were made (True for live mode, # None for test mode). if datapipeline_ret['result'] in [True, None]: ret['result'] = datapipeline_ret['result'] comments.append(datapipeline_ret['comment']) if datapipeline_ret.get('changes'): ret['changes']['backup_datapipeline_{0}'.format(config['name'])] = \ datapipeline_ret.get('changes'), else: ret['comment'] = ',\n'.join([ret['comment'], datapipeline_ret['comment']]) _add_changes(ret, changes_old, changes_new) return ret ret['comment'] = ',\n'.join(comments) _add_changes(ret, changes_old, changes_new) return ret
[ "def", "present", "(", "name", "=", "None", ",", "table_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "read_capacity_units", "=", "None", ",", "write_capacity_units",...
Ensure the DynamoDB table exists. Table throughput can be updated after table creation. Global secondary indexes (GSIs) are managed with some exceptions: - If a GSI deletion is detected, a failure will occur (deletes should be done manually in the AWS console). - If multiple GSIs are added in a single Salt call, a failure will occur (boto supports one creation at a time). Note that this only applies after table creation; multiple GSIs can be created during table creation. - Updates to existing GSIs are limited to read/write capacity only (DynamoDB limitation). name Name of the DynamoDB table table_name Name of the DynamoDB table (deprecated) region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. read_capacity_units The read throughput for this table write_capacity_units The write throughput for this table hash_key The name of the attribute that will be used as the hash key for this table hash_key_data_type The DynamoDB datatype of the hash key range_key The name of the attribute that will be used as the range key for this table range_key_data_type The DynamoDB datatype of the range key local_indexes The local indexes you would like to create global_indexes The global indexes you would like to create backup_configs_from_pillars Pillars to use to configure DataPipeline backups
[ "Ensure", "the", "DynamoDB", "table", "exists", ".", "Table", "throughput", "can", "be", "updated", "after", "table", "creation", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_dynamodb.py#L190-L425
train
saltstack/salt
salt/states/boto_dynamodb.py
_global_indexes_present
def _global_indexes_present(provisioned_indexes, global_indexes, changes_old, changes_new, comments, name, region, key, keyid, profile): '''Handles global secondary index for the table present state.''' ret = {'result': True} if provisioned_indexes: provisioned_gsi_config = dict((index['IndexName'], index) for index in provisioned_indexes) else: provisioned_gsi_config = {} provisioned_index_names = set(provisioned_gsi_config.keys()) # Map of index name to given Salt config for this run. This loop is complicated # because global_indexes is made up of OrderedDicts and lists. gsi_config = {} if global_indexes: for index in global_indexes: # Each index config is a key that maps to a list of OrderedDicts. index_config = index.values()[0] index_name = None for entry in index_config: # Key by the name field in the index config. if entry.keys() == ['name']: index_name = entry.values()[0] if not index_name: ret['result'] = False ret['comment'] = 'Index name not found for table {0}'.format(name) return ret gsi_config[index_name] = index existing_index_names, new_index_names, index_names_to_be_deleted = _partition_index_names( provisioned_index_names, set(gsi_config.keys())) if index_names_to_be_deleted: ret['result'] = False ret['comment'] = ('Deletion of GSIs ({0}) is not supported! Please do this ' 'manually in the AWS console.'.format(', '.join(index_names_to_be_deleted))) return ret elif len(new_index_names) > 1: ret['result'] = False ret['comment'] = ('Creation of multiple GSIs ({0}) is not supported due to API ' 'limitations. Please create them one at a time.'.format(new_index_names)) return ret if new_index_names: # Given the length check above, new_index_names should have a single element here. index_name = next(iter(new_index_names)) _add_global_secondary_index(ret, name, index_name, changes_old, changes_new, comments, gsi_config, region, key, keyid, profile) if not ret['result']: return ret if existing_index_names: _update_global_secondary_indexes(ret, changes_old, changes_new, comments, existing_index_names, provisioned_gsi_config, gsi_config, name, region, key, keyid, profile) if not ret['result']: return ret if 'global_indexes' not in changes_old and 'global_indexes' not in changes_new: comments.append('All global secondary indexes match') return ret
python
def _global_indexes_present(provisioned_indexes, global_indexes, changes_old, changes_new, comments, name, region, key, keyid, profile): '''Handles global secondary index for the table present state.''' ret = {'result': True} if provisioned_indexes: provisioned_gsi_config = dict((index['IndexName'], index) for index in provisioned_indexes) else: provisioned_gsi_config = {} provisioned_index_names = set(provisioned_gsi_config.keys()) # Map of index name to given Salt config for this run. This loop is complicated # because global_indexes is made up of OrderedDicts and lists. gsi_config = {} if global_indexes: for index in global_indexes: # Each index config is a key that maps to a list of OrderedDicts. index_config = index.values()[0] index_name = None for entry in index_config: # Key by the name field in the index config. if entry.keys() == ['name']: index_name = entry.values()[0] if not index_name: ret['result'] = False ret['comment'] = 'Index name not found for table {0}'.format(name) return ret gsi_config[index_name] = index existing_index_names, new_index_names, index_names_to_be_deleted = _partition_index_names( provisioned_index_names, set(gsi_config.keys())) if index_names_to_be_deleted: ret['result'] = False ret['comment'] = ('Deletion of GSIs ({0}) is not supported! Please do this ' 'manually in the AWS console.'.format(', '.join(index_names_to_be_deleted))) return ret elif len(new_index_names) > 1: ret['result'] = False ret['comment'] = ('Creation of multiple GSIs ({0}) is not supported due to API ' 'limitations. Please create them one at a time.'.format(new_index_names)) return ret if new_index_names: # Given the length check above, new_index_names should have a single element here. index_name = next(iter(new_index_names)) _add_global_secondary_index(ret, name, index_name, changes_old, changes_new, comments, gsi_config, region, key, keyid, profile) if not ret['result']: return ret if existing_index_names: _update_global_secondary_indexes(ret, changes_old, changes_new, comments, existing_index_names, provisioned_gsi_config, gsi_config, name, region, key, keyid, profile) if not ret['result']: return ret if 'global_indexes' not in changes_old and 'global_indexes' not in changes_new: comments.append('All global secondary indexes match') return ret
[ "def", "_global_indexes_present", "(", "provisioned_indexes", ",", "global_indexes", ",", "changes_old", ",", "changes_new", ",", "comments", ",", "name", ",", "region", ",", "key", ",", "keyid", ",", "profile", ")", ":", "ret", "=", "{", "'result'", ":", "T...
Handles global secondary index for the table present state.
[ "Handles", "global", "secondary", "index", "for", "the", "table", "present", "state", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_dynamodb.py#L435-L495
train
saltstack/salt
salt/states/boto_dynamodb.py
_partition_index_names
def _partition_index_names(provisioned_index_names, index_names): '''Returns 3 disjoint sets of indexes: existing, to be created, and to be deleted.''' existing_index_names = set() new_index_names = set() for name in index_names: if name in provisioned_index_names: existing_index_names.add(name) else: new_index_names.add(name) index_names_to_be_deleted = provisioned_index_names - existing_index_names return existing_index_names, new_index_names, index_names_to_be_deleted
python
def _partition_index_names(provisioned_index_names, index_names): '''Returns 3 disjoint sets of indexes: existing, to be created, and to be deleted.''' existing_index_names = set() new_index_names = set() for name in index_names: if name in provisioned_index_names: existing_index_names.add(name) else: new_index_names.add(name) index_names_to_be_deleted = provisioned_index_names - existing_index_names return existing_index_names, new_index_names, index_names_to_be_deleted
[ "def", "_partition_index_names", "(", "provisioned_index_names", ",", "index_names", ")", ":", "existing_index_names", "=", "set", "(", ")", "new_index_names", "=", "set", "(", ")", "for", "name", "in", "index_names", ":", "if", "name", "in", "provisioned_index_na...
Returns 3 disjoint sets of indexes: existing, to be created, and to be deleted.
[ "Returns", "3", "disjoint", "sets", "of", "indexes", ":", "existing", "to", "be", "created", "and", "to", "be", "deleted", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_dynamodb.py#L498-L508
train
saltstack/salt
salt/states/boto_dynamodb.py
_add_global_secondary_index
def _add_global_secondary_index(ret, name, index_name, changes_old, changes_new, comments, gsi_config, region, key, keyid, profile): '''Updates ret iff there was a failure or in test mode.''' if __opts__['test']: ret['result'] = None ret['comment'] = 'Dynamo table {0} will have a GSI added: {1}'.format( name, index_name) return changes_new.setdefault('global_indexes', {}) success = __salt__['boto_dynamodb.create_global_secondary_index']( name, __salt__['boto_dynamodb.extract_index']( gsi_config[index_name], global_index=True), region=region, key=key, keyid=keyid, profile=profile, ) if success: comments.append('Created GSI {0}'.format(index_name)) changes_new['global_indexes'][index_name] = gsi_config[index_name] else: ret['result'] = False ret['comment'] = 'Failed to create GSI {0}'.format(index_name)
python
def _add_global_secondary_index(ret, name, index_name, changes_old, changes_new, comments, gsi_config, region, key, keyid, profile): '''Updates ret iff there was a failure or in test mode.''' if __opts__['test']: ret['result'] = None ret['comment'] = 'Dynamo table {0} will have a GSI added: {1}'.format( name, index_name) return changes_new.setdefault('global_indexes', {}) success = __salt__['boto_dynamodb.create_global_secondary_index']( name, __salt__['boto_dynamodb.extract_index']( gsi_config[index_name], global_index=True), region=region, key=key, keyid=keyid, profile=profile, ) if success: comments.append('Created GSI {0}'.format(index_name)) changes_new['global_indexes'][index_name] = gsi_config[index_name] else: ret['result'] = False ret['comment'] = 'Failed to create GSI {0}'.format(index_name)
[ "def", "_add_global_secondary_index", "(", "ret", ",", "name", ",", "index_name", ",", "changes_old", ",", "changes_new", ",", "comments", ",", "gsi_config", ",", "region", ",", "key", ",", "keyid", ",", "profile", ")", ":", "if", "__opts__", "[", "'test'", ...
Updates ret iff there was a failure or in test mode.
[ "Updates", "ret", "iff", "there", "was", "a", "failure", "or", "in", "test", "mode", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_dynamodb.py#L511-L535
train
saltstack/salt
salt/states/boto_dynamodb.py
_update_global_secondary_indexes
def _update_global_secondary_indexes(ret, changes_old, changes_new, comments, existing_index_names, provisioned_gsi_config, gsi_config, name, region, key, keyid, profile): '''Updates ret iff there was a failure or in test mode.''' try: provisioned_throughputs, index_updates = _determine_gsi_updates( existing_index_names, provisioned_gsi_config, gsi_config) except GsiNotUpdatableError as e: ret['result'] = False ret['comment'] = six.text_type(e) return if index_updates: if __opts__['test']: ret['result'] = None ret['comment'] = 'Dynamo table {0} will have GSIs updated: {1}'.format( name, ', '.join(index_updates.keys())) return changes_old.setdefault('global_indexes', {}) changes_new.setdefault('global_indexes', {}) success = __salt__['boto_dynamodb.update_global_secondary_index']( name, index_updates, region=region, key=key, keyid=keyid, profile=profile, ) if success: comments.append( 'Updated GSIs with new throughputs {0}'.format(index_updates)) for index_name in index_updates: changes_old['global_indexes'][index_name] = provisioned_throughputs[index_name] changes_new['global_indexes'][index_name] = index_updates[index_name] else: ret['result'] = False ret['comment'] = 'Failed to update GSI throughputs {0}'.format(index_updates)
python
def _update_global_secondary_indexes(ret, changes_old, changes_new, comments, existing_index_names, provisioned_gsi_config, gsi_config, name, region, key, keyid, profile): '''Updates ret iff there was a failure or in test mode.''' try: provisioned_throughputs, index_updates = _determine_gsi_updates( existing_index_names, provisioned_gsi_config, gsi_config) except GsiNotUpdatableError as e: ret['result'] = False ret['comment'] = six.text_type(e) return if index_updates: if __opts__['test']: ret['result'] = None ret['comment'] = 'Dynamo table {0} will have GSIs updated: {1}'.format( name, ', '.join(index_updates.keys())) return changes_old.setdefault('global_indexes', {}) changes_new.setdefault('global_indexes', {}) success = __salt__['boto_dynamodb.update_global_secondary_index']( name, index_updates, region=region, key=key, keyid=keyid, profile=profile, ) if success: comments.append( 'Updated GSIs with new throughputs {0}'.format(index_updates)) for index_name in index_updates: changes_old['global_indexes'][index_name] = provisioned_throughputs[index_name] changes_new['global_indexes'][index_name] = index_updates[index_name] else: ret['result'] = False ret['comment'] = 'Failed to update GSI throughputs {0}'.format(index_updates)
[ "def", "_update_global_secondary_indexes", "(", "ret", ",", "changes_old", ",", "changes_new", ",", "comments", ",", "existing_index_names", ",", "provisioned_gsi_config", ",", "gsi_config", ",", "name", ",", "region", ",", "key", ",", "keyid", ",", "profile", ")"...
Updates ret iff there was a failure or in test mode.
[ "Updates", "ret", "iff", "there", "was", "a", "failure", "or", "in", "test", "mode", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_dynamodb.py#L538-L575
train
saltstack/salt
salt/states/boto_dynamodb.py
_alarms_present
def _alarms_present(name, alarms, alarms_from_pillar, write_capacity_units, read_capacity_units, region, key, keyid, profile): '''helper method for present. ensure that cloudwatch_alarms are set''' # load data from alarms_from_pillar tmp = copy.deepcopy( __salt__['config.option'](alarms_from_pillar, {}) ) # merge with data from alarms if alarms: tmp = dictupdate.update(tmp, alarms) # set alarms, using boto_cloudwatch_alarm.present merged_return_value = {'name': name, 'result': True, 'comment': '', 'changes': {}} for _, info in six.iteritems(tmp): # add dynamodb table to name and description info["name"] = name + " " + info["name"] info["attributes"]["description"] = name + " " + info["attributes"]["description"] # add dimension attribute info["attributes"]["dimensions"] = {"TableName": [name]} if info["attributes"]["metric"] == "ConsumedWriteCapacityUnits" \ and "threshold" not in info["attributes"]: info["attributes"]["threshold"] = math.ceil(write_capacity_units * info["attributes"]["threshold_percent"]) del info["attributes"]["threshold_percent"] # the write_capacity_units is given in unit / second. So we need # to multiply by the period to get the proper threshold. # http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/MonitoringDynamoDB.html info["attributes"]["threshold"] *= info["attributes"]["period"] if info["attributes"]["metric"] == "ConsumedReadCapacityUnits" \ and "threshold" not in info["attributes"]: info["attributes"]["threshold"] = math.ceil(read_capacity_units * info["attributes"]["threshold_percent"]) del info["attributes"]["threshold_percent"] # the read_capacity_units is given in unit / second. So we need # to multiply by the period to get the proper threshold. # http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/MonitoringDynamoDB.html info["attributes"]["threshold"] *= info["attributes"]["period"] # set alarm kwargs = { "name": info["name"], "attributes": info["attributes"], "region": region, "key": key, "keyid": keyid, "profile": profile, } results = __states__['boto_cloudwatch_alarm.present'](**kwargs) if not results["result"]: merged_return_value["result"] = results["result"] if results.get("changes", {}) != {}: merged_return_value["changes"][info["name"]] = results["changes"] if "comment" in results: merged_return_value["comment"] += results["comment"] return merged_return_value
python
def _alarms_present(name, alarms, alarms_from_pillar, write_capacity_units, read_capacity_units, region, key, keyid, profile): '''helper method for present. ensure that cloudwatch_alarms are set''' # load data from alarms_from_pillar tmp = copy.deepcopy( __salt__['config.option'](alarms_from_pillar, {}) ) # merge with data from alarms if alarms: tmp = dictupdate.update(tmp, alarms) # set alarms, using boto_cloudwatch_alarm.present merged_return_value = {'name': name, 'result': True, 'comment': '', 'changes': {}} for _, info in six.iteritems(tmp): # add dynamodb table to name and description info["name"] = name + " " + info["name"] info["attributes"]["description"] = name + " " + info["attributes"]["description"] # add dimension attribute info["attributes"]["dimensions"] = {"TableName": [name]} if info["attributes"]["metric"] == "ConsumedWriteCapacityUnits" \ and "threshold" not in info["attributes"]: info["attributes"]["threshold"] = math.ceil(write_capacity_units * info["attributes"]["threshold_percent"]) del info["attributes"]["threshold_percent"] # the write_capacity_units is given in unit / second. So we need # to multiply by the period to get the proper threshold. # http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/MonitoringDynamoDB.html info["attributes"]["threshold"] *= info["attributes"]["period"] if info["attributes"]["metric"] == "ConsumedReadCapacityUnits" \ and "threshold" not in info["attributes"]: info["attributes"]["threshold"] = math.ceil(read_capacity_units * info["attributes"]["threshold_percent"]) del info["attributes"]["threshold_percent"] # the read_capacity_units is given in unit / second. So we need # to multiply by the period to get the proper threshold. # http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/MonitoringDynamoDB.html info["attributes"]["threshold"] *= info["attributes"]["period"] # set alarm kwargs = { "name": info["name"], "attributes": info["attributes"], "region": region, "key": key, "keyid": keyid, "profile": profile, } results = __states__['boto_cloudwatch_alarm.present'](**kwargs) if not results["result"]: merged_return_value["result"] = results["result"] if results.get("changes", {}) != {}: merged_return_value["changes"][info["name"]] = results["changes"] if "comment" in results: merged_return_value["comment"] += results["comment"] return merged_return_value
[ "def", "_alarms_present", "(", "name", ",", "alarms", ",", "alarms_from_pillar", ",", "write_capacity_units", ",", "read_capacity_units", ",", "region", ",", "key", ",", "keyid", ",", "profile", ")", ":", "# load data from alarms_from_pillar", "tmp", "=", "copy", ...
helper method for present. ensure that cloudwatch_alarms are set
[ "helper", "method", "for", "present", ".", "ensure", "that", "cloudwatch_alarms", "are", "set" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_dynamodb.py#L617-L668
train
saltstack/salt
salt/states/boto_dynamodb.py
_next_datetime_with_utc_hour
def _next_datetime_with_utc_hour(table_name, utc_hour): ''' Datapipeline API is throttling us, as all the pipelines are started at the same time. We would like to uniformly distribute the startTime over a 60 minute window. Return the next future utc datetime where hour == utc_hour minute = A value between 0-59 (depending on table name) second = A value between 0-59 (depending on table name) ''' today = datetime.date.today() # The minute and second values generated are deterministic, as we do not want # pipeline definition to change for every run. start_date_time = datetime.datetime( year=today.year, month=today.month, day=today.day, hour=utc_hour, minute=_get_deterministic_value_for_table_name(table_name, 60), second=_get_deterministic_value_for_table_name(table_name, 60) ) if start_date_time < datetime.datetime.utcnow(): one_day = datetime.timedelta(days=1) start_date_time += one_day return start_date_time
python
def _next_datetime_with_utc_hour(table_name, utc_hour): ''' Datapipeline API is throttling us, as all the pipelines are started at the same time. We would like to uniformly distribute the startTime over a 60 minute window. Return the next future utc datetime where hour == utc_hour minute = A value between 0-59 (depending on table name) second = A value between 0-59 (depending on table name) ''' today = datetime.date.today() # The minute and second values generated are deterministic, as we do not want # pipeline definition to change for every run. start_date_time = datetime.datetime( year=today.year, month=today.month, day=today.day, hour=utc_hour, minute=_get_deterministic_value_for_table_name(table_name, 60), second=_get_deterministic_value_for_table_name(table_name, 60) ) if start_date_time < datetime.datetime.utcnow(): one_day = datetime.timedelta(days=1) start_date_time += one_day return start_date_time
[ "def", "_next_datetime_with_utc_hour", "(", "table_name", ",", "utc_hour", ")", ":", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", "# The minute and second values generated are deterministic, as we do not want", "# pipeline definition to change for every run.", ...
Datapipeline API is throttling us, as all the pipelines are started at the same time. We would like to uniformly distribute the startTime over a 60 minute window. Return the next future utc datetime where hour == utc_hour minute = A value between 0-59 (depending on table name) second = A value between 0-59 (depending on table name)
[ "Datapipeline", "API", "is", "throttling", "us", "as", "all", "the", "pipelines", "are", "started", "at", "the", "same", "time", ".", "We", "would", "like", "to", "uniformly", "distribute", "the", "startTime", "over", "a", "60", "minute", "window", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_dynamodb.py#L701-L728
train
saltstack/salt
salt/runners/winrepo.py
genrepo
def genrepo(opts=None, fire_event=True): ''' Generate winrepo_cachefile based on sls files in the winrepo_dir opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. fire_event : True Fire an event on failure. Only supported on the master. CLI Example: .. code-block:: bash salt-run winrepo.genrepo ''' if opts is None: opts = __opts__ winrepo_dir = opts['winrepo_dir'] winrepo_cachefile = opts['winrepo_cachefile'] ret = {} if not os.path.exists(winrepo_dir): os.makedirs(winrepo_dir) renderers = salt.loader.render(opts, __salt__) for root, _, files in salt.utils.path.os_walk(winrepo_dir): for name in files: if name.endswith('.sls'): try: config = salt.template.compile_template( os.path.join(root, name), renderers, opts['renderer'], opts['renderer_blacklist'], opts['renderer_whitelist'] ) except SaltRenderError as exc: log.debug( 'Failed to render %s.', os.path.join(root, name) ) log.debug('Error: %s.', exc) continue if config: revmap = {} for pkgname, versions in six.iteritems(config): log.debug( 'Compiling winrepo data for package \'%s\'', pkgname ) for version, repodata in six.iteritems(versions): log.debug( 'Compiling winrepo data for %s version %s', pkgname, version ) if not isinstance(version, six.string_types): config[pkgname][six.text_type(version)] = \ config[pkgname].pop(version) if not isinstance(repodata, dict): msg = 'Failed to compile {0}.'.format( os.path.join(root, name) ) log.debug(msg) if fire_event: try: __jid_event__.fire_event( {'error': msg}, 'progress' ) except NameError: log.error( 'Attempted to fire the an event ' 'with the following error, but ' 'event firing is not supported: %s', msg ) continue revmap[repodata['full_name']] = pkgname ret.setdefault('repo', {}).update(config) ret.setdefault('name_map', {}).update(revmap) with salt.utils.files.fopen( os.path.join(winrepo_dir, winrepo_cachefile), 'w+b') as repo: repo.write(salt.utils.msgpack.dumps(ret)) return ret
python
def genrepo(opts=None, fire_event=True): ''' Generate winrepo_cachefile based on sls files in the winrepo_dir opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. fire_event : True Fire an event on failure. Only supported on the master. CLI Example: .. code-block:: bash salt-run winrepo.genrepo ''' if opts is None: opts = __opts__ winrepo_dir = opts['winrepo_dir'] winrepo_cachefile = opts['winrepo_cachefile'] ret = {} if not os.path.exists(winrepo_dir): os.makedirs(winrepo_dir) renderers = salt.loader.render(opts, __salt__) for root, _, files in salt.utils.path.os_walk(winrepo_dir): for name in files: if name.endswith('.sls'): try: config = salt.template.compile_template( os.path.join(root, name), renderers, opts['renderer'], opts['renderer_blacklist'], opts['renderer_whitelist'] ) except SaltRenderError as exc: log.debug( 'Failed to render %s.', os.path.join(root, name) ) log.debug('Error: %s.', exc) continue if config: revmap = {} for pkgname, versions in six.iteritems(config): log.debug( 'Compiling winrepo data for package \'%s\'', pkgname ) for version, repodata in six.iteritems(versions): log.debug( 'Compiling winrepo data for %s version %s', pkgname, version ) if not isinstance(version, six.string_types): config[pkgname][six.text_type(version)] = \ config[pkgname].pop(version) if not isinstance(repodata, dict): msg = 'Failed to compile {0}.'.format( os.path.join(root, name) ) log.debug(msg) if fire_event: try: __jid_event__.fire_event( {'error': msg}, 'progress' ) except NameError: log.error( 'Attempted to fire the an event ' 'with the following error, but ' 'event firing is not supported: %s', msg ) continue revmap[repodata['full_name']] = pkgname ret.setdefault('repo', {}).update(config) ret.setdefault('name_map', {}).update(revmap) with salt.utils.files.fopen( os.path.join(winrepo_dir, winrepo_cachefile), 'w+b') as repo: repo.write(salt.utils.msgpack.dumps(ret)) return ret
[ "def", "genrepo", "(", "opts", "=", "None", ",", "fire_event", "=", "True", ")", ":", "if", "opts", "is", "None", ":", "opts", "=", "__opts__", "winrepo_dir", "=", "opts", "[", "'winrepo_dir'", "]", "winrepo_cachefile", "=", "opts", "[", "'winrepo_cachefil...
Generate winrepo_cachefile based on sls files in the winrepo_dir opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. fire_event : True Fire an event on failure. Only supported on the master. CLI Example: .. code-block:: bash salt-run winrepo.genrepo
[ "Generate", "winrepo_cachefile", "based", "on", "sls", "files", "in", "the", "winrepo_dir" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/winrepo.py#L40-L125
train
saltstack/salt
salt/runners/winrepo.py
update_git_repos
def update_git_repos(opts=None, clean=False, masterless=False): ''' Checkout git repos containing Windows Software Package Definitions opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. clean : False Clean repo cachedirs which are not configured under :conf_master:`winrepo_remotes`. .. warning:: This argument should not be set to ``True`` if a mix of git and non-git repo definitions are being used, as it will result in the non-git repo definitions being removed. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-run winrepo.update_git_repos salt-run winrepo.update_git_repos clean=True ''' if opts is None: opts = __opts__ winrepo_dir = opts['winrepo_dir'] winrepo_remotes = opts['winrepo_remotes'] winrepo_cfg = [(winrepo_remotes, winrepo_dir), (opts['winrepo_remotes_ng'], opts['winrepo_dir_ng'])] ret = {} for remotes, base_dir in winrepo_cfg: if not any((salt.utils.gitfs.GITPYTHON_VERSION, salt.utils.gitfs.PYGIT2_VERSION)): # Use legacy code winrepo_result = {} for remote_info in remotes: if '/' in remote_info: targetname = remote_info.split('/')[-1] else: targetname = remote_info rev = 'HEAD' # If a revision is specified, use it. try: rev, remote_url = remote_info.strip().split() except ValueError: remote_url = remote_info gittarget = os.path.join(base_dir, targetname).replace('.', '_') if masterless: result = __salt__['state.single']('git.latest', name=remote_url, rev=rev, branch='winrepo', target=gittarget, force_checkout=True, force_reset=True) if isinstance(result, list): # Errors were detected raise CommandExecutionError( 'Failed up update winrepo remotes: {0}'.format( '\n'.join(result) ) ) if 'name' not in result: # Highstate output dict, the results are actually nested # one level down. key = next(iter(result)) result = result[key] else: mminion = salt.minion.MasterMinion(opts) result = mminion.states['git.latest'](remote_url, rev=rev, branch='winrepo', target=gittarget, force_checkout=True, force_reset=True) winrepo_result[result['name']] = result['result'] ret.update(winrepo_result) else: # New winrepo code utilizing salt.utils.gitfs try: winrepo = salt.utils.gitfs.WinRepo( opts, remotes, per_remote_overrides=PER_REMOTE_OVERRIDES, per_remote_only=PER_REMOTE_ONLY, global_only=GLOBAL_ONLY, cache_root=base_dir) winrepo.fetch_remotes() # Since we're not running update(), we need to manually call # clear_old_remotes() to remove directories from remotes that # have been removed from configuration. if clean: winrepo.clear_old_remotes() winrepo.checkout() except Exception as exc: msg = 'Failed to update winrepo_remotes: {0}'.format(exc) log.error(msg, exc_info_on_loglevel=logging.DEBUG) return msg ret.update(winrepo.winrepo_dirs) return ret
python
def update_git_repos(opts=None, clean=False, masterless=False): ''' Checkout git repos containing Windows Software Package Definitions opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. clean : False Clean repo cachedirs which are not configured under :conf_master:`winrepo_remotes`. .. warning:: This argument should not be set to ``True`` if a mix of git and non-git repo definitions are being used, as it will result in the non-git repo definitions being removed. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-run winrepo.update_git_repos salt-run winrepo.update_git_repos clean=True ''' if opts is None: opts = __opts__ winrepo_dir = opts['winrepo_dir'] winrepo_remotes = opts['winrepo_remotes'] winrepo_cfg = [(winrepo_remotes, winrepo_dir), (opts['winrepo_remotes_ng'], opts['winrepo_dir_ng'])] ret = {} for remotes, base_dir in winrepo_cfg: if not any((salt.utils.gitfs.GITPYTHON_VERSION, salt.utils.gitfs.PYGIT2_VERSION)): # Use legacy code winrepo_result = {} for remote_info in remotes: if '/' in remote_info: targetname = remote_info.split('/')[-1] else: targetname = remote_info rev = 'HEAD' # If a revision is specified, use it. try: rev, remote_url = remote_info.strip().split() except ValueError: remote_url = remote_info gittarget = os.path.join(base_dir, targetname).replace('.', '_') if masterless: result = __salt__['state.single']('git.latest', name=remote_url, rev=rev, branch='winrepo', target=gittarget, force_checkout=True, force_reset=True) if isinstance(result, list): # Errors were detected raise CommandExecutionError( 'Failed up update winrepo remotes: {0}'.format( '\n'.join(result) ) ) if 'name' not in result: # Highstate output dict, the results are actually nested # one level down. key = next(iter(result)) result = result[key] else: mminion = salt.minion.MasterMinion(opts) result = mminion.states['git.latest'](remote_url, rev=rev, branch='winrepo', target=gittarget, force_checkout=True, force_reset=True) winrepo_result[result['name']] = result['result'] ret.update(winrepo_result) else: # New winrepo code utilizing salt.utils.gitfs try: winrepo = salt.utils.gitfs.WinRepo( opts, remotes, per_remote_overrides=PER_REMOTE_OVERRIDES, per_remote_only=PER_REMOTE_ONLY, global_only=GLOBAL_ONLY, cache_root=base_dir) winrepo.fetch_remotes() # Since we're not running update(), we need to manually call # clear_old_remotes() to remove directories from remotes that # have been removed from configuration. if clean: winrepo.clear_old_remotes() winrepo.checkout() except Exception as exc: msg = 'Failed to update winrepo_remotes: {0}'.format(exc) log.error(msg, exc_info_on_loglevel=logging.DEBUG) return msg ret.update(winrepo.winrepo_dirs) return ret
[ "def", "update_git_repos", "(", "opts", "=", "None", ",", "clean", "=", "False", ",", "masterless", "=", "False", ")", ":", "if", "opts", "is", "None", ":", "opts", "=", "__opts__", "winrepo_dir", "=", "opts", "[", "'winrepo_dir'", "]", "winrepo_remotes", ...
Checkout git repos containing Windows Software Package Definitions opts Specify an alternate opts dict. Should not be used unless this function is imported into an execution module. clean : False Clean repo cachedirs which are not configured under :conf_master:`winrepo_remotes`. .. warning:: This argument should not be set to ``True`` if a mix of git and non-git repo definitions are being used, as it will result in the non-git repo definitions being removed. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt-run winrepo.update_git_repos salt-run winrepo.update_git_repos clean=True
[ "Checkout", "git", "repos", "containing", "Windows", "Software", "Package", "Definitions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/winrepo.py#L128-L233
train
saltstack/salt
salt/utils/extmods.py
sync
def sync(opts, form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None): ''' Sync custom modules into the extension_modules directory ''' if saltenv is None: saltenv = ['base'] if extmod_whitelist is None: extmod_whitelist = opts['extmod_whitelist'] elif isinstance(extmod_whitelist, six.string_types): extmod_whitelist = {form: extmod_whitelist.split(',')} elif not isinstance(extmod_whitelist, dict): log.error('extmod_whitelist must be a string or dictionary: %s', extmod_whitelist) if extmod_blacklist is None: extmod_blacklist = opts['extmod_blacklist'] elif isinstance(extmod_blacklist, six.string_types): extmod_blacklist = {form: extmod_blacklist.split(',')} elif not isinstance(extmod_blacklist, dict): log.error('extmod_blacklist must be a string or dictionary: %s', extmod_blacklist) if isinstance(saltenv, six.string_types): saltenv = saltenv.split(',') ret = [] remote = set() source = salt.utils.url.create('_' + form) mod_dir = os.path.join(opts['extension_modules'], '{0}'.format(form)) touched = False with salt.utils.files.set_umask(0o077): try: if not os.path.isdir(mod_dir): log.info('Creating module dir \'%s\'', mod_dir) try: os.makedirs(mod_dir) except (IOError, OSError): log.error( 'Cannot create cache module directory %s. Check ' 'permissions.', mod_dir ) fileclient = salt.fileclient.get_file_client(opts) for sub_env in saltenv: log.info( 'Syncing %s for environment \'%s\'', form, sub_env ) cache = [] log.info('Loading cache from %s, for %s', source, sub_env) # Grab only the desired files (.py, .pyx, .so) cache.extend( fileclient.cache_dir( source, sub_env, include_empty=False, include_pat=r'E@\.(pyx?|so|zip)$', exclude_pat=None ) ) local_cache_dir = os.path.join( opts['cachedir'], 'files', sub_env, '_{0}'.format(form) ) log.debug('Local cache dir: \'%s\'', local_cache_dir) for fn_ in cache: relpath = os.path.relpath(fn_, local_cache_dir) relname = os.path.splitext(relpath)[0].replace(os.sep, '.') if extmod_whitelist and form in extmod_whitelist and relname not in extmod_whitelist[form]: continue if extmod_blacklist and form in extmod_blacklist and relname in extmod_blacklist[form]: continue remote.add(relpath) dest = os.path.join(mod_dir, relpath) log.info('Copying \'%s\' to \'%s\'', fn_, dest) if os.path.isfile(dest): # The file is present, if the sum differs replace it hash_type = opts.get('hash_type', 'md5') src_digest = salt.utils.hashutils.get_hash(fn_, hash_type) dst_digest = salt.utils.hashutils.get_hash(dest, hash_type) if src_digest != dst_digest: # The downloaded file differs, replace! shutil.copyfile(fn_, dest) ret.append('{0}.{1}'.format(form, relname)) else: dest_dir = os.path.dirname(dest) if not os.path.isdir(dest_dir): os.makedirs(dest_dir) shutil.copyfile(fn_, dest) ret.append('{0}.{1}'.format(form, relname)) # If the synchronized module is an utils # directory, we add it to sys.path for util_dir in opts['utils_dirs']: if mod_dir.endswith(util_dir) and mod_dir not in sys.path: sys.path.append(mod_dir) touched = bool(ret) if opts['clean_dynamic_modules'] is True: current = set(_listdir_recursively(mod_dir)) for fn_ in current - remote: full = os.path.join(mod_dir, fn_) if os.path.isfile(full): touched = True os.remove(full) # Cleanup empty dirs while True: emptydirs = _list_emptydirs(mod_dir) if not emptydirs: break for emptydir in emptydirs: touched = True shutil.rmtree(emptydir, ignore_errors=True) except Exception as exc: log.error('Failed to sync %s module: %s', form, exc) return ret, touched
python
def sync(opts, form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None): ''' Sync custom modules into the extension_modules directory ''' if saltenv is None: saltenv = ['base'] if extmod_whitelist is None: extmod_whitelist = opts['extmod_whitelist'] elif isinstance(extmod_whitelist, six.string_types): extmod_whitelist = {form: extmod_whitelist.split(',')} elif not isinstance(extmod_whitelist, dict): log.error('extmod_whitelist must be a string or dictionary: %s', extmod_whitelist) if extmod_blacklist is None: extmod_blacklist = opts['extmod_blacklist'] elif isinstance(extmod_blacklist, six.string_types): extmod_blacklist = {form: extmod_blacklist.split(',')} elif not isinstance(extmod_blacklist, dict): log.error('extmod_blacklist must be a string or dictionary: %s', extmod_blacklist) if isinstance(saltenv, six.string_types): saltenv = saltenv.split(',') ret = [] remote = set() source = salt.utils.url.create('_' + form) mod_dir = os.path.join(opts['extension_modules'], '{0}'.format(form)) touched = False with salt.utils.files.set_umask(0o077): try: if not os.path.isdir(mod_dir): log.info('Creating module dir \'%s\'', mod_dir) try: os.makedirs(mod_dir) except (IOError, OSError): log.error( 'Cannot create cache module directory %s. Check ' 'permissions.', mod_dir ) fileclient = salt.fileclient.get_file_client(opts) for sub_env in saltenv: log.info( 'Syncing %s for environment \'%s\'', form, sub_env ) cache = [] log.info('Loading cache from %s, for %s', source, sub_env) # Grab only the desired files (.py, .pyx, .so) cache.extend( fileclient.cache_dir( source, sub_env, include_empty=False, include_pat=r'E@\.(pyx?|so|zip)$', exclude_pat=None ) ) local_cache_dir = os.path.join( opts['cachedir'], 'files', sub_env, '_{0}'.format(form) ) log.debug('Local cache dir: \'%s\'', local_cache_dir) for fn_ in cache: relpath = os.path.relpath(fn_, local_cache_dir) relname = os.path.splitext(relpath)[0].replace(os.sep, '.') if extmod_whitelist and form in extmod_whitelist and relname not in extmod_whitelist[form]: continue if extmod_blacklist and form in extmod_blacklist and relname in extmod_blacklist[form]: continue remote.add(relpath) dest = os.path.join(mod_dir, relpath) log.info('Copying \'%s\' to \'%s\'', fn_, dest) if os.path.isfile(dest): # The file is present, if the sum differs replace it hash_type = opts.get('hash_type', 'md5') src_digest = salt.utils.hashutils.get_hash(fn_, hash_type) dst_digest = salt.utils.hashutils.get_hash(dest, hash_type) if src_digest != dst_digest: # The downloaded file differs, replace! shutil.copyfile(fn_, dest) ret.append('{0}.{1}'.format(form, relname)) else: dest_dir = os.path.dirname(dest) if not os.path.isdir(dest_dir): os.makedirs(dest_dir) shutil.copyfile(fn_, dest) ret.append('{0}.{1}'.format(form, relname)) # If the synchronized module is an utils # directory, we add it to sys.path for util_dir in opts['utils_dirs']: if mod_dir.endswith(util_dir) and mod_dir not in sys.path: sys.path.append(mod_dir) touched = bool(ret) if opts['clean_dynamic_modules'] is True: current = set(_listdir_recursively(mod_dir)) for fn_ in current - remote: full = os.path.join(mod_dir, fn_) if os.path.isfile(full): touched = True os.remove(full) # Cleanup empty dirs while True: emptydirs = _list_emptydirs(mod_dir) if not emptydirs: break for emptydir in emptydirs: touched = True shutil.rmtree(emptydir, ignore_errors=True) except Exception as exc: log.error('Failed to sync %s module: %s', form, exc) return ret, touched
[ "def", "sync", "(", "opts", ",", "form", ",", "saltenv", "=", "None", ",", "extmod_whitelist", "=", "None", ",", "extmod_blacklist", "=", "None", ")", ":", "if", "saltenv", "is", "None", ":", "saltenv", "=", "[", "'base'", "]", "if", "extmod_whitelist", ...
Sync custom modules into the extension_modules directory
[ "Sync", "custom", "modules", "into", "the", "extension_modules", "directory" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/extmods.py#L43-L159
train
saltstack/salt
salt/states/saltmod.py
_parallel_map
def _parallel_map(func, inputs): ''' Applies a function to each element of a list, returning the resulting list. A separate thread is created for each element in the input list and the passed function is called for each of the elements. When all threads have finished execution a list with the results corresponding to the inputs is returned. If one of the threads fails (because the function throws an exception), that exception is reraised. If more than one thread fails, the exception from the first thread (according to the index of the input element) is reraised. func: function that is applied on each input element. inputs: list of elements that shall be processed. The length of this list also defines the number of threads created. ''' outputs = len(inputs) * [None] errors = len(inputs) * [None] def create_thread(index): def run_thread(): try: outputs[index] = func(inputs[index]) except: # pylint: disable=bare-except errors[index] = sys.exc_info() thread = threading.Thread(target=run_thread) thread.start() return thread threads = list(six.moves.map(create_thread, six.moves.range(len(inputs)))) for thread in threads: thread.join() for error in errors: if error is not None: exc_type, exc_value, exc_traceback = error six.reraise(exc_type, exc_value, exc_traceback) return outputs
python
def _parallel_map(func, inputs): ''' Applies a function to each element of a list, returning the resulting list. A separate thread is created for each element in the input list and the passed function is called for each of the elements. When all threads have finished execution a list with the results corresponding to the inputs is returned. If one of the threads fails (because the function throws an exception), that exception is reraised. If more than one thread fails, the exception from the first thread (according to the index of the input element) is reraised. func: function that is applied on each input element. inputs: list of elements that shall be processed. The length of this list also defines the number of threads created. ''' outputs = len(inputs) * [None] errors = len(inputs) * [None] def create_thread(index): def run_thread(): try: outputs[index] = func(inputs[index]) except: # pylint: disable=bare-except errors[index] = sys.exc_info() thread = threading.Thread(target=run_thread) thread.start() return thread threads = list(six.moves.map(create_thread, six.moves.range(len(inputs)))) for thread in threads: thread.join() for error in errors: if error is not None: exc_type, exc_value, exc_traceback = error six.reraise(exc_type, exc_value, exc_traceback) return outputs
[ "def", "_parallel_map", "(", "func", ",", "inputs", ")", ":", "outputs", "=", "len", "(", "inputs", ")", "*", "[", "None", "]", "errors", "=", "len", "(", "inputs", ")", "*", "[", "None", "]", "def", "create_thread", "(", "index", ")", ":", "def", ...
Applies a function to each element of a list, returning the resulting list. A separate thread is created for each element in the input list and the passed function is called for each of the elements. When all threads have finished execution a list with the results corresponding to the inputs is returned. If one of the threads fails (because the function throws an exception), that exception is reraised. If more than one thread fails, the exception from the first thread (according to the index of the input element) is reraised. func: function that is applied on each input element. inputs: list of elements that shall be processed. The length of this list also defines the number of threads created.
[ "Applies", "a", "function", "to", "each", "element", "of", "a", "list", "returning", "the", "resulting", "list", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltmod.py#L66-L105
train
saltstack/salt
salt/states/saltmod.py
state
def state(name, tgt, ssh=False, tgt_type='glob', ret='', ret_config=None, ret_kwargs=None, highstate=None, sls=None, top=None, saltenv=None, test=None, pillar=None, pillarenv=None, expect_minions=True, fail_minions=None, allow_fail=0, exclude=None, concurrent=False, timeout=None, batch=None, queue=False, subset=None, orchestration_jid=None, **kwargs): ''' Invoke a state run on a given target name An arbitrary name used to track the state execution tgt The target specification for the state run. .. versionadded: 2016.11.0 Masterless support: When running on a masterless minion, the ``tgt`` is ignored and will always be the local minion. tgt_type The target type to resolve, defaults to ``glob`` ret Optionally set a single or a list of returners to use ret_config Use an alternative returner configuration ret_kwargs Override individual returner configuration items highstate Defaults to None, if set to True the target systems will ignore any sls references specified in the sls option and call state.highstate on the targeted minions top Should be the name of a top file. If set state.top is called with this top file instead of state.sls. sls A group of sls files to execute. This can be defined as a single string containing a single sls file, or a list of sls files test Pass ``test=true`` or ``test=false`` through to the state function. This can be used to overide a test mode set in the minion's config file. If left as the default of None and the 'test' mode is supplied on the command line, that value is passed instead. pillar Pass the ``pillar`` kwarg through to the state function pillarenv The pillar environment to grab pillars from .. versionadded:: 2017.7.0 saltenv The default salt environment to pull sls files from ssh Set to `True` to use the ssh client instead of the standard salt client roster In the event of using salt-ssh, a roster system can be set expect_minions An optional boolean for failing if some minions do not respond fail_minions An optional list of targeted minions where failure is an option allow_fail Pass in the number of minions to allow for failure before setting the result of the execution to False exclude Pass exclude kwarg to state concurrent Allow multiple state runs to occur at once. WARNING: This flag is potentially dangerous. It is designed for use when multiple state runs can safely be run at the same Do not use this flag for performance optimization. queue Pass ``queue=true`` through to the state function batch Execute the command :ref:`in batches <targeting-batch>`. E.g.: ``10%``. .. versionadded:: 2016.3.0 subset Number of minions from the targeted set to randomly use .. versionadded:: 2017.7.0 asynchronous Run the salt command but don't wait for a reply. NOTE: This flag conflicts with subset and batch flags and cannot be used at the same time. .. versionadded:: neon Examples: Run a list of sls files via :py:func:`state.sls <salt.state.sls>` on target minions: .. code-block:: yaml webservers: salt.state: - tgt: 'web*' - sls: - apache - django - core - saltenv: prod Run sls file via :py:func:`state.sls <salt.state.sls>` on target minions with exclude: .. code-block:: yaml docker: salt.state: - tgt: 'docker*' - sls: docker - exclude: docker.swarm - saltenv: prod Run a full :py:func:`state.highstate <salt.state.highstate>` on target mininons. .. code-block:: yaml databases: salt.state: - tgt: role:database - tgt_type: grain - highstate: True ''' cmd_kw = {'arg': [], 'kwarg': {}, 'ret': ret, 'timeout': timeout} if ret_config: cmd_kw['ret_config'] = ret_config if ret_kwargs: cmd_kw['ret_kwargs'] = ret_kwargs state_ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} try: allow_fail = int(allow_fail) except ValueError: state_ret['result'] = False state_ret['comment'] = 'Passed invalid value for \'allow_fail\', must be an int' return state_ret cmd_kw['tgt_type'] = tgt_type cmd_kw['ssh'] = ssh if 'roster' in kwargs: cmd_kw['roster'] = kwargs['roster'] cmd_kw['expect_minions'] = expect_minions cmd_kw['asynchronous'] = kwargs.pop('asynchronous', False) if highstate: fun = 'state.highstate' elif top: fun = 'state.top' cmd_kw['arg'].append(top) elif sls: fun = 'state.sls' if isinstance(sls, list): sls = ','.join(sls) cmd_kw['arg'].append(sls) else: state_ret['comment'] = 'No highstate or sls specified, no execution made' state_ret['result'] = False return state_ret if test is not None or __opts__.get('test'): cmd_kw['kwarg']['test'] = test if test is not None else __opts__.get('test') if pillar: cmd_kw['kwarg']['pillar'] = pillar if pillarenv is not None: cmd_kw['kwarg']['pillarenv'] = pillarenv if saltenv is not None: cmd_kw['kwarg']['saltenv'] = saltenv if exclude is not None: cmd_kw['kwarg']['exclude'] = exclude cmd_kw['kwarg']['queue'] = queue if isinstance(concurrent, bool): cmd_kw['kwarg']['concurrent'] = concurrent else: state_ret['comment'] = ('Must pass in boolean for value of \'concurrent\'') state_ret['result'] = False return state_ret if batch is not None: cmd_kw['batch'] = six.text_type(batch) if subset is not None: cmd_kw['subset'] = subset masterless = __opts__['__role'] == 'minion' and \ __opts__['file_client'] == 'local' if not masterless: _fire_args({'type': 'state', 'tgt': tgt, 'name': name, 'args': cmd_kw}) cmd_ret = __salt__['saltutil.cmd'](tgt, fun, **cmd_kw) else: if top: cmd_kw['topfn'] = ''.join(cmd_kw.pop('arg')) elif sls: cmd_kw['mods'] = ''.join(cmd_kw.pop('arg')) cmd_kw.update(cmd_kw.pop('kwarg')) tmp_ret = __salt__[fun](**cmd_kw) cmd_ret = {__opts__['id']: { 'ret': tmp_ret, 'out': tmp_ret.get('out', 'highstate') if isinstance(tmp_ret, dict) else 'highstate' }} if cmd_kw['asynchronous']: state_ret['__jid__'] = cmd_ret.get('jid') state_ret['changes'] = cmd_ret if int(cmd_ret.get('jid', 0)) > 0: state_ret['result'] = True state_ret['comment'] = 'State submitted successfully.' else: state_ret['result'] = False state_ret['comment'] = 'State failed to run.' return state_ret try: state_ret['__jid__'] = cmd_ret[next(iter(cmd_ret))]['jid'] except (StopIteration, KeyError): pass changes = {} fail = set() no_change = set() if fail_minions is None: fail_minions = () elif isinstance(fail_minions, six.string_types): fail_minions = [minion.strip() for minion in fail_minions.split(',')] elif not isinstance(fail_minions, list): state_ret.setdefault('warnings', []).append( '\'fail_minions\' needs to be a list or a comma separated ' 'string. Ignored.' ) fail_minions = () if not cmd_ret and expect_minions: state_ret['result'] = False state_ret['comment'] = 'No minions returned' return state_ret for minion, mdata in six.iteritems(cmd_ret): if mdata.get('out', '') != 'highstate': log.warning('Output from salt state not highstate') m_ret = False if 'return' in mdata and 'ret' not in mdata: mdata['ret'] = mdata.pop('return') m_state = True if mdata.get('failed', False): m_state = False else: try: m_ret = mdata['ret'] except KeyError: m_state = False if m_state: m_state = __utils__['state.check_result'](m_ret, recurse=True) if not m_state: if minion not in fail_minions: fail.add(minion) changes[minion] = m_ret continue try: for state_item in six.itervalues(m_ret): if isinstance(state_item, dict): if 'changes' in state_item and state_item['changes']: changes[minion] = m_ret break else: no_change.add(minion) except AttributeError: log.error("m_ret did not have changes %s %s", type(m_ret), m_ret) no_change.add(minion) if changes: state_ret['changes'] = {'out': 'highstate', 'ret': changes} if len(fail) > allow_fail: state_ret['result'] = False state_ret['comment'] = 'Run failed on minions: {0}'.format(', '.join(fail)) else: state_ret['comment'] = 'States ran successfully.' if changes: state_ret['comment'] += ' Updating {0}.'.format(', '.join(changes)) if no_change: state_ret['comment'] += ' No changes made to {0}.'.format(', '.join(no_change)) if test or __opts__.get('test'): if state_ret['changes'] and state_ret['result'] is True: # Test mode with changes is the only case where result should ever be none state_ret['result'] = None return state_ret
python
def state(name, tgt, ssh=False, tgt_type='glob', ret='', ret_config=None, ret_kwargs=None, highstate=None, sls=None, top=None, saltenv=None, test=None, pillar=None, pillarenv=None, expect_minions=True, fail_minions=None, allow_fail=0, exclude=None, concurrent=False, timeout=None, batch=None, queue=False, subset=None, orchestration_jid=None, **kwargs): ''' Invoke a state run on a given target name An arbitrary name used to track the state execution tgt The target specification for the state run. .. versionadded: 2016.11.0 Masterless support: When running on a masterless minion, the ``tgt`` is ignored and will always be the local minion. tgt_type The target type to resolve, defaults to ``glob`` ret Optionally set a single or a list of returners to use ret_config Use an alternative returner configuration ret_kwargs Override individual returner configuration items highstate Defaults to None, if set to True the target systems will ignore any sls references specified in the sls option and call state.highstate on the targeted minions top Should be the name of a top file. If set state.top is called with this top file instead of state.sls. sls A group of sls files to execute. This can be defined as a single string containing a single sls file, or a list of sls files test Pass ``test=true`` or ``test=false`` through to the state function. This can be used to overide a test mode set in the minion's config file. If left as the default of None and the 'test' mode is supplied on the command line, that value is passed instead. pillar Pass the ``pillar`` kwarg through to the state function pillarenv The pillar environment to grab pillars from .. versionadded:: 2017.7.0 saltenv The default salt environment to pull sls files from ssh Set to `True` to use the ssh client instead of the standard salt client roster In the event of using salt-ssh, a roster system can be set expect_minions An optional boolean for failing if some minions do not respond fail_minions An optional list of targeted minions where failure is an option allow_fail Pass in the number of minions to allow for failure before setting the result of the execution to False exclude Pass exclude kwarg to state concurrent Allow multiple state runs to occur at once. WARNING: This flag is potentially dangerous. It is designed for use when multiple state runs can safely be run at the same Do not use this flag for performance optimization. queue Pass ``queue=true`` through to the state function batch Execute the command :ref:`in batches <targeting-batch>`. E.g.: ``10%``. .. versionadded:: 2016.3.0 subset Number of minions from the targeted set to randomly use .. versionadded:: 2017.7.0 asynchronous Run the salt command but don't wait for a reply. NOTE: This flag conflicts with subset and batch flags and cannot be used at the same time. .. versionadded:: neon Examples: Run a list of sls files via :py:func:`state.sls <salt.state.sls>` on target minions: .. code-block:: yaml webservers: salt.state: - tgt: 'web*' - sls: - apache - django - core - saltenv: prod Run sls file via :py:func:`state.sls <salt.state.sls>` on target minions with exclude: .. code-block:: yaml docker: salt.state: - tgt: 'docker*' - sls: docker - exclude: docker.swarm - saltenv: prod Run a full :py:func:`state.highstate <salt.state.highstate>` on target mininons. .. code-block:: yaml databases: salt.state: - tgt: role:database - tgt_type: grain - highstate: True ''' cmd_kw = {'arg': [], 'kwarg': {}, 'ret': ret, 'timeout': timeout} if ret_config: cmd_kw['ret_config'] = ret_config if ret_kwargs: cmd_kw['ret_kwargs'] = ret_kwargs state_ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} try: allow_fail = int(allow_fail) except ValueError: state_ret['result'] = False state_ret['comment'] = 'Passed invalid value for \'allow_fail\', must be an int' return state_ret cmd_kw['tgt_type'] = tgt_type cmd_kw['ssh'] = ssh if 'roster' in kwargs: cmd_kw['roster'] = kwargs['roster'] cmd_kw['expect_minions'] = expect_minions cmd_kw['asynchronous'] = kwargs.pop('asynchronous', False) if highstate: fun = 'state.highstate' elif top: fun = 'state.top' cmd_kw['arg'].append(top) elif sls: fun = 'state.sls' if isinstance(sls, list): sls = ','.join(sls) cmd_kw['arg'].append(sls) else: state_ret['comment'] = 'No highstate or sls specified, no execution made' state_ret['result'] = False return state_ret if test is not None or __opts__.get('test'): cmd_kw['kwarg']['test'] = test if test is not None else __opts__.get('test') if pillar: cmd_kw['kwarg']['pillar'] = pillar if pillarenv is not None: cmd_kw['kwarg']['pillarenv'] = pillarenv if saltenv is not None: cmd_kw['kwarg']['saltenv'] = saltenv if exclude is not None: cmd_kw['kwarg']['exclude'] = exclude cmd_kw['kwarg']['queue'] = queue if isinstance(concurrent, bool): cmd_kw['kwarg']['concurrent'] = concurrent else: state_ret['comment'] = ('Must pass in boolean for value of \'concurrent\'') state_ret['result'] = False return state_ret if batch is not None: cmd_kw['batch'] = six.text_type(batch) if subset is not None: cmd_kw['subset'] = subset masterless = __opts__['__role'] == 'minion' and \ __opts__['file_client'] == 'local' if not masterless: _fire_args({'type': 'state', 'tgt': tgt, 'name': name, 'args': cmd_kw}) cmd_ret = __salt__['saltutil.cmd'](tgt, fun, **cmd_kw) else: if top: cmd_kw['topfn'] = ''.join(cmd_kw.pop('arg')) elif sls: cmd_kw['mods'] = ''.join(cmd_kw.pop('arg')) cmd_kw.update(cmd_kw.pop('kwarg')) tmp_ret = __salt__[fun](**cmd_kw) cmd_ret = {__opts__['id']: { 'ret': tmp_ret, 'out': tmp_ret.get('out', 'highstate') if isinstance(tmp_ret, dict) else 'highstate' }} if cmd_kw['asynchronous']: state_ret['__jid__'] = cmd_ret.get('jid') state_ret['changes'] = cmd_ret if int(cmd_ret.get('jid', 0)) > 0: state_ret['result'] = True state_ret['comment'] = 'State submitted successfully.' else: state_ret['result'] = False state_ret['comment'] = 'State failed to run.' return state_ret try: state_ret['__jid__'] = cmd_ret[next(iter(cmd_ret))]['jid'] except (StopIteration, KeyError): pass changes = {} fail = set() no_change = set() if fail_minions is None: fail_minions = () elif isinstance(fail_minions, six.string_types): fail_minions = [minion.strip() for minion in fail_minions.split(',')] elif not isinstance(fail_minions, list): state_ret.setdefault('warnings', []).append( '\'fail_minions\' needs to be a list or a comma separated ' 'string. Ignored.' ) fail_minions = () if not cmd_ret and expect_minions: state_ret['result'] = False state_ret['comment'] = 'No minions returned' return state_ret for minion, mdata in six.iteritems(cmd_ret): if mdata.get('out', '') != 'highstate': log.warning('Output from salt state not highstate') m_ret = False if 'return' in mdata and 'ret' not in mdata: mdata['ret'] = mdata.pop('return') m_state = True if mdata.get('failed', False): m_state = False else: try: m_ret = mdata['ret'] except KeyError: m_state = False if m_state: m_state = __utils__['state.check_result'](m_ret, recurse=True) if not m_state: if minion not in fail_minions: fail.add(minion) changes[minion] = m_ret continue try: for state_item in six.itervalues(m_ret): if isinstance(state_item, dict): if 'changes' in state_item and state_item['changes']: changes[minion] = m_ret break else: no_change.add(minion) except AttributeError: log.error("m_ret did not have changes %s %s", type(m_ret), m_ret) no_change.add(minion) if changes: state_ret['changes'] = {'out': 'highstate', 'ret': changes} if len(fail) > allow_fail: state_ret['result'] = False state_ret['comment'] = 'Run failed on minions: {0}'.format(', '.join(fail)) else: state_ret['comment'] = 'States ran successfully.' if changes: state_ret['comment'] += ' Updating {0}.'.format(', '.join(changes)) if no_change: state_ret['comment'] += ' No changes made to {0}.'.format(', '.join(no_change)) if test or __opts__.get('test'): if state_ret['changes'] and state_ret['result'] is True: # Test mode with changes is the only case where result should ever be none state_ret['result'] = None return state_ret
[ "def", "state", "(", "name", ",", "tgt", ",", "ssh", "=", "False", ",", "tgt_type", "=", "'glob'", ",", "ret", "=", "''", ",", "ret_config", "=", "None", ",", "ret_kwargs", "=", "None", ",", "highstate", "=", "None", ",", "sls", "=", "None", ",", ...
Invoke a state run on a given target name An arbitrary name used to track the state execution tgt The target specification for the state run. .. versionadded: 2016.11.0 Masterless support: When running on a masterless minion, the ``tgt`` is ignored and will always be the local minion. tgt_type The target type to resolve, defaults to ``glob`` ret Optionally set a single or a list of returners to use ret_config Use an alternative returner configuration ret_kwargs Override individual returner configuration items highstate Defaults to None, if set to True the target systems will ignore any sls references specified in the sls option and call state.highstate on the targeted minions top Should be the name of a top file. If set state.top is called with this top file instead of state.sls. sls A group of sls files to execute. This can be defined as a single string containing a single sls file, or a list of sls files test Pass ``test=true`` or ``test=false`` through to the state function. This can be used to overide a test mode set in the minion's config file. If left as the default of None and the 'test' mode is supplied on the command line, that value is passed instead. pillar Pass the ``pillar`` kwarg through to the state function pillarenv The pillar environment to grab pillars from .. versionadded:: 2017.7.0 saltenv The default salt environment to pull sls files from ssh Set to `True` to use the ssh client instead of the standard salt client roster In the event of using salt-ssh, a roster system can be set expect_minions An optional boolean for failing if some minions do not respond fail_minions An optional list of targeted minions where failure is an option allow_fail Pass in the number of minions to allow for failure before setting the result of the execution to False exclude Pass exclude kwarg to state concurrent Allow multiple state runs to occur at once. WARNING: This flag is potentially dangerous. It is designed for use when multiple state runs can safely be run at the same Do not use this flag for performance optimization. queue Pass ``queue=true`` through to the state function batch Execute the command :ref:`in batches <targeting-batch>`. E.g.: ``10%``. .. versionadded:: 2016.3.0 subset Number of minions from the targeted set to randomly use .. versionadded:: 2017.7.0 asynchronous Run the salt command but don't wait for a reply. NOTE: This flag conflicts with subset and batch flags and cannot be used at the same time. .. versionadded:: neon Examples: Run a list of sls files via :py:func:`state.sls <salt.state.sls>` on target minions: .. code-block:: yaml webservers: salt.state: - tgt: 'web*' - sls: - apache - django - core - saltenv: prod Run sls file via :py:func:`state.sls <salt.state.sls>` on target minions with exclude: .. code-block:: yaml docker: salt.state: - tgt: 'docker*' - sls: docker - exclude: docker.swarm - saltenv: prod Run a full :py:func:`state.highstate <salt.state.highstate>` on target mininons. .. code-block:: yaml databases: salt.state: - tgt: role:database - tgt_type: grain - highstate: True
[ "Invoke", "a", "state", "run", "on", "a", "given", "target" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltmod.py#L108-L452
train
saltstack/salt
salt/states/saltmod.py
function
def function( name, tgt, ssh=False, tgt_type='glob', ret='', ret_config=None, ret_kwargs=None, expect_minions=False, fail_minions=None, fail_function=None, arg=None, kwarg=None, timeout=None, batch=None, subset=None, **kwargs): # pylint: disable=unused-argument ''' Execute a single module function on a remote minion via salt or salt-ssh name The name of the function to run, aka cmd.run or pkg.install tgt The target specification, aka '*' for all minions tgt_type The target type, defaults to ``glob`` arg The list of arguments to pass into the function kwarg The dict (not a list) of keyword arguments to pass into the function ret Optionally set a single or a list of returners to use ret_config Use an alternative returner configuration ret_kwargs Override individual returner configuration items expect_minions An optional boolean for failing if some minions do not respond fail_minions An optional list of targeted minions where failure is an option fail_function An optional string that points to a salt module that returns True or False based on the returned data dict for individual minions ssh Set to `True` to use the ssh client instead of the standard salt client batch Execute the command :ref:`in batches <targeting-batch>`. E.g.: ``10%``. subset Number of minions from the targeted set to randomly use .. versionadded:: 2017.7.0 asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon ''' func_ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if kwarg is None: kwarg = {} if isinstance(arg, six.string_types): func_ret['warnings'] = [ 'Please specify \'arg\' as a list of arguments.' ] arg = arg.split() cmd_kw = {'arg': arg or [], 'kwarg': kwarg, 'ret': ret, 'timeout': timeout} if batch is not None: cmd_kw['batch'] = six.text_type(batch) if subset is not None: cmd_kw['subset'] = subset cmd_kw['tgt_type'] = tgt_type cmd_kw['ssh'] = ssh cmd_kw['expect_minions'] = expect_minions cmd_kw['_cmd_meta'] = True cmd_kw['asynchronous'] = kwargs.pop('asynchronous', False) if ret_config: cmd_kw['ret_config'] = ret_config if ret_kwargs: cmd_kw['ret_kwargs'] = ret_kwargs fun = name if __opts__['test'] is True: func_ret['comment'] = \ 'Function {0} would be executed on target {1}'.format(fun, tgt) func_ret['result'] = None return func_ret try: _fire_args({'type': 'function', 'tgt': tgt, 'name': name, 'args': cmd_kw}) cmd_ret = __salt__['saltutil.cmd'](tgt, fun, **cmd_kw) except Exception as exc: func_ret['result'] = False func_ret['comment'] = six.text_type(exc) return func_ret if cmd_kw['asynchronous']: func_ret['__jid__'] = cmd_ret.get('jid') func_ret['changes'] = cmd_ret if int(cmd_ret.get('jid', 0)) > 0: func_ret['result'] = True func_ret['comment'] = 'Function submitted successfully.' else: func_ret['result'] = False func_ret['comment'] = 'Function failed to run.' return func_ret try: func_ret['__jid__'] = cmd_ret[next(iter(cmd_ret))]['jid'] except (StopIteration, KeyError): pass changes = {} fail = set() if fail_minions is None: fail_minions = () elif isinstance(fail_minions, six.string_types): fail_minions = [minion.strip() for minion in fail_minions.split(',')] elif not isinstance(fail_minions, list): func_ret.setdefault('warnings', []).append( '\'fail_minions\' needs to be a list or a comma separated ' 'string. Ignored.' ) fail_minions = () for minion, mdata in six.iteritems(cmd_ret): m_ret = False if mdata.get('retcode'): func_ret['result'] = False fail.add(minion) if mdata.get('failed', False): m_func = False else: if 'return' in mdata and 'ret' not in mdata: mdata['ret'] = mdata.pop('return') m_ret = mdata['ret'] m_func = (not fail_function and True) or __salt__[fail_function](m_ret) if m_ret is False: m_func = False if not m_func: if minion not in fail_minions: fail.add(minion) changes[minion] = m_ret if not cmd_ret: func_ret['result'] = False func_ret['command'] = 'No minions responded' else: if changes: func_ret['changes'] = {'out': 'highstate', 'ret': changes} if fail: func_ret['result'] = False func_ret['comment'] = 'Running function {0} failed on minions: {1}'.format(name, ', '.join(fail)) else: func_ret['comment'] = 'Function ran successfully.' if changes: func_ret['comment'] += ' Function {0} ran on {1}.'.format(name, ', '.join(changes)) return func_ret
python
def function( name, tgt, ssh=False, tgt_type='glob', ret='', ret_config=None, ret_kwargs=None, expect_minions=False, fail_minions=None, fail_function=None, arg=None, kwarg=None, timeout=None, batch=None, subset=None, **kwargs): # pylint: disable=unused-argument ''' Execute a single module function on a remote minion via salt or salt-ssh name The name of the function to run, aka cmd.run or pkg.install tgt The target specification, aka '*' for all minions tgt_type The target type, defaults to ``glob`` arg The list of arguments to pass into the function kwarg The dict (not a list) of keyword arguments to pass into the function ret Optionally set a single or a list of returners to use ret_config Use an alternative returner configuration ret_kwargs Override individual returner configuration items expect_minions An optional boolean for failing if some minions do not respond fail_minions An optional list of targeted minions where failure is an option fail_function An optional string that points to a salt module that returns True or False based on the returned data dict for individual minions ssh Set to `True` to use the ssh client instead of the standard salt client batch Execute the command :ref:`in batches <targeting-batch>`. E.g.: ``10%``. subset Number of minions from the targeted set to randomly use .. versionadded:: 2017.7.0 asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon ''' func_ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if kwarg is None: kwarg = {} if isinstance(arg, six.string_types): func_ret['warnings'] = [ 'Please specify \'arg\' as a list of arguments.' ] arg = arg.split() cmd_kw = {'arg': arg or [], 'kwarg': kwarg, 'ret': ret, 'timeout': timeout} if batch is not None: cmd_kw['batch'] = six.text_type(batch) if subset is not None: cmd_kw['subset'] = subset cmd_kw['tgt_type'] = tgt_type cmd_kw['ssh'] = ssh cmd_kw['expect_minions'] = expect_minions cmd_kw['_cmd_meta'] = True cmd_kw['asynchronous'] = kwargs.pop('asynchronous', False) if ret_config: cmd_kw['ret_config'] = ret_config if ret_kwargs: cmd_kw['ret_kwargs'] = ret_kwargs fun = name if __opts__['test'] is True: func_ret['comment'] = \ 'Function {0} would be executed on target {1}'.format(fun, tgt) func_ret['result'] = None return func_ret try: _fire_args({'type': 'function', 'tgt': tgt, 'name': name, 'args': cmd_kw}) cmd_ret = __salt__['saltutil.cmd'](tgt, fun, **cmd_kw) except Exception as exc: func_ret['result'] = False func_ret['comment'] = six.text_type(exc) return func_ret if cmd_kw['asynchronous']: func_ret['__jid__'] = cmd_ret.get('jid') func_ret['changes'] = cmd_ret if int(cmd_ret.get('jid', 0)) > 0: func_ret['result'] = True func_ret['comment'] = 'Function submitted successfully.' else: func_ret['result'] = False func_ret['comment'] = 'Function failed to run.' return func_ret try: func_ret['__jid__'] = cmd_ret[next(iter(cmd_ret))]['jid'] except (StopIteration, KeyError): pass changes = {} fail = set() if fail_minions is None: fail_minions = () elif isinstance(fail_minions, six.string_types): fail_minions = [minion.strip() for minion in fail_minions.split(',')] elif not isinstance(fail_minions, list): func_ret.setdefault('warnings', []).append( '\'fail_minions\' needs to be a list or a comma separated ' 'string. Ignored.' ) fail_minions = () for minion, mdata in six.iteritems(cmd_ret): m_ret = False if mdata.get('retcode'): func_ret['result'] = False fail.add(minion) if mdata.get('failed', False): m_func = False else: if 'return' in mdata and 'ret' not in mdata: mdata['ret'] = mdata.pop('return') m_ret = mdata['ret'] m_func = (not fail_function and True) or __salt__[fail_function](m_ret) if m_ret is False: m_func = False if not m_func: if minion not in fail_minions: fail.add(minion) changes[minion] = m_ret if not cmd_ret: func_ret['result'] = False func_ret['command'] = 'No minions responded' else: if changes: func_ret['changes'] = {'out': 'highstate', 'ret': changes} if fail: func_ret['result'] = False func_ret['comment'] = 'Running function {0} failed on minions: {1}'.format(name, ', '.join(fail)) else: func_ret['comment'] = 'Function ran successfully.' if changes: func_ret['comment'] += ' Function {0} ran on {1}.'.format(name, ', '.join(changes)) return func_ret
[ "def", "function", "(", "name", ",", "tgt", ",", "ssh", "=", "False", ",", "tgt_type", "=", "'glob'", ",", "ret", "=", "''", ",", "ret_config", "=", "None", ",", "ret_kwargs", "=", "None", ",", "expect_minions", "=", "False", ",", "fail_minions", "=", ...
Execute a single module function on a remote minion via salt or salt-ssh name The name of the function to run, aka cmd.run or pkg.install tgt The target specification, aka '*' for all minions tgt_type The target type, defaults to ``glob`` arg The list of arguments to pass into the function kwarg The dict (not a list) of keyword arguments to pass into the function ret Optionally set a single or a list of returners to use ret_config Use an alternative returner configuration ret_kwargs Override individual returner configuration items expect_minions An optional boolean for failing if some minions do not respond fail_minions An optional list of targeted minions where failure is an option fail_function An optional string that points to a salt module that returns True or False based on the returned data dict for individual minions ssh Set to `True` to use the ssh client instead of the standard salt client batch Execute the command :ref:`in batches <targeting-batch>`. E.g.: ``10%``. subset Number of minions from the targeted set to randomly use .. versionadded:: 2017.7.0 asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon
[ "Execute", "a", "single", "module", "function", "on", "a", "remote", "minion", "via", "salt", "or", "salt", "-", "ssh" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltmod.py#L455-L633
train
saltstack/salt
salt/states/saltmod.py
wait_for_event
def wait_for_event( name, id_list, event_id='id', timeout=300, node='master'): ''' Watch Salt's event bus and block until a condition is met .. versionadded:: 2014.7.0 name An event tag to watch for; supports Reactor-style globbing. id_list A list of event identifiers to watch for -- usually the minion ID. Each time an event tag is matched the event data is inspected for ``event_id``, if found it is removed from ``id_list``. When ``id_list`` is empty this function returns success. event_id : id The name of a key in the event data. Default is ``id`` for the minion ID, another common value is ``name`` for use with orchestrating salt-cloud events. timeout : 300 The maximum time in seconds to wait before failing. The following example blocks until all the listed minions complete a restart and reconnect to the Salt master: .. code-block:: yaml reboot_all_minions: salt.function: - name: system.reboot - tgt: '*' wait_for_reboots: salt.wait_for_event: - name: salt/minion/*/start - id_list: - jerry - stuart - dave - phil - kevin - mike - require: - salt: reboot_all_minions ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} if __opts__.get('test'): ret['comment'] = \ 'Orchestration would wait for event \'{0}\''.format(name) ret['result'] = None return ret sevent = salt.utils.event.get_event( node, __opts__['sock_dir'], __opts__['transport'], opts=__opts__, listen=True) del_counter = 0 starttime = time.time() timelimit = starttime + timeout while True: event = sevent.get_event(full=True) is_timedout = time.time() > timelimit if event is None and not is_timedout: log.trace("wait_for_event: No event data; waiting.") continue elif event is None and is_timedout: ret['comment'] = 'Timeout value reached.' return ret if fnmatch.fnmatch(event['tag'], name): val = event['data'].get(event_id) if val is None and 'data' in event['data']: val = event['data']['data'].get(event_id) if val is not None: try: val_idx = id_list.index(val) except ValueError: log.trace("wait_for_event: Event identifier '%s' not in " "id_list; skipping.", event_id) else: del id_list[val_idx] del_counter += 1 minions_seen = ret['changes'].setdefault('minions_seen', []) minions_seen.append(val) log.debug("wait_for_event: Event identifier '%s' removed " "from id_list; %s items remaining.", val, len(id_list)) else: log.trace("wait_for_event: Event identifier '%s' not in event " "'%s'; skipping.", event_id, event['tag']) else: log.debug("wait_for_event: Skipping unmatched event '%s'", event['tag']) if not id_list: ret['result'] = True ret['comment'] = 'All events seen in {0} seconds.'.format( time.time() - starttime) return ret if is_timedout: ret['comment'] = 'Timeout value reached.' return ret
python
def wait_for_event( name, id_list, event_id='id', timeout=300, node='master'): ''' Watch Salt's event bus and block until a condition is met .. versionadded:: 2014.7.0 name An event tag to watch for; supports Reactor-style globbing. id_list A list of event identifiers to watch for -- usually the minion ID. Each time an event tag is matched the event data is inspected for ``event_id``, if found it is removed from ``id_list``. When ``id_list`` is empty this function returns success. event_id : id The name of a key in the event data. Default is ``id`` for the minion ID, another common value is ``name`` for use with orchestrating salt-cloud events. timeout : 300 The maximum time in seconds to wait before failing. The following example blocks until all the listed minions complete a restart and reconnect to the Salt master: .. code-block:: yaml reboot_all_minions: salt.function: - name: system.reboot - tgt: '*' wait_for_reboots: salt.wait_for_event: - name: salt/minion/*/start - id_list: - jerry - stuart - dave - phil - kevin - mike - require: - salt: reboot_all_minions ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} if __opts__.get('test'): ret['comment'] = \ 'Orchestration would wait for event \'{0}\''.format(name) ret['result'] = None return ret sevent = salt.utils.event.get_event( node, __opts__['sock_dir'], __opts__['transport'], opts=__opts__, listen=True) del_counter = 0 starttime = time.time() timelimit = starttime + timeout while True: event = sevent.get_event(full=True) is_timedout = time.time() > timelimit if event is None and not is_timedout: log.trace("wait_for_event: No event data; waiting.") continue elif event is None and is_timedout: ret['comment'] = 'Timeout value reached.' return ret if fnmatch.fnmatch(event['tag'], name): val = event['data'].get(event_id) if val is None and 'data' in event['data']: val = event['data']['data'].get(event_id) if val is not None: try: val_idx = id_list.index(val) except ValueError: log.trace("wait_for_event: Event identifier '%s' not in " "id_list; skipping.", event_id) else: del id_list[val_idx] del_counter += 1 minions_seen = ret['changes'].setdefault('minions_seen', []) minions_seen.append(val) log.debug("wait_for_event: Event identifier '%s' removed " "from id_list; %s items remaining.", val, len(id_list)) else: log.trace("wait_for_event: Event identifier '%s' not in event " "'%s'; skipping.", event_id, event['tag']) else: log.debug("wait_for_event: Skipping unmatched event '%s'", event['tag']) if not id_list: ret['result'] = True ret['comment'] = 'All events seen in {0} seconds.'.format( time.time() - starttime) return ret if is_timedout: ret['comment'] = 'Timeout value reached.' return ret
[ "def", "wait_for_event", "(", "name", ",", "id_list", ",", "event_id", "=", "'id'", ",", "timeout", "=", "300", ",", "node", "=", "'master'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", ...
Watch Salt's event bus and block until a condition is met .. versionadded:: 2014.7.0 name An event tag to watch for; supports Reactor-style globbing. id_list A list of event identifiers to watch for -- usually the minion ID. Each time an event tag is matched the event data is inspected for ``event_id``, if found it is removed from ``id_list``. When ``id_list`` is empty this function returns success. event_id : id The name of a key in the event data. Default is ``id`` for the minion ID, another common value is ``name`` for use with orchestrating salt-cloud events. timeout : 300 The maximum time in seconds to wait before failing. The following example blocks until all the listed minions complete a restart and reconnect to the Salt master: .. code-block:: yaml reboot_all_minions: salt.function: - name: system.reboot - tgt: '*' wait_for_reboots: salt.wait_for_event: - name: salt/minion/*/start - id_list: - jerry - stuart - dave - phil - kevin - mike - require: - salt: reboot_all_minions
[ "Watch", "Salt", "s", "event", "bus", "and", "block", "until", "a", "condition", "is", "met" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltmod.py#L636-L748
train
saltstack/salt
salt/states/saltmod.py
runner
def runner(name, **kwargs): ''' Execute a runner module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the runner function asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon .. code-block:: yaml run-manage-up: salt.runner: - name: manage.up ''' try: jid = __orchestration_jid__ except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__' ) jid = None if __opts__.get('test', False): ret = { 'name': name, 'result': None, 'changes': {}, 'comment': "Runner function '{0}' would be executed.".format(name) } return ret out = __salt__['saltutil.runner'](name, __orchestration_jid__=jid, __env__=__env__, full_return=True, **kwargs) if kwargs.get('asynchronous'): out['return'] = out.copy() out['success'] = 'jid' in out and 'tag' in out runner_return = out.get('return') if isinstance(runner_return, dict) and 'Error' in runner_return: out['success'] = False success = out.get('success', True) ret = {'name': name, 'changes': {'return': runner_return}, 'result': success} ret['comment'] = "Runner function '{0}' {1}.".format( name, 'executed' if success else 'failed', ) ret['__orchestration__'] = True if 'jid' in out: ret['__jid__'] = out['jid'] return ret
python
def runner(name, **kwargs): ''' Execute a runner module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the runner function asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon .. code-block:: yaml run-manage-up: salt.runner: - name: manage.up ''' try: jid = __orchestration_jid__ except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__' ) jid = None if __opts__.get('test', False): ret = { 'name': name, 'result': None, 'changes': {}, 'comment': "Runner function '{0}' would be executed.".format(name) } return ret out = __salt__['saltutil.runner'](name, __orchestration_jid__=jid, __env__=__env__, full_return=True, **kwargs) if kwargs.get('asynchronous'): out['return'] = out.copy() out['success'] = 'jid' in out and 'tag' in out runner_return = out.get('return') if isinstance(runner_return, dict) and 'Error' in runner_return: out['success'] = False success = out.get('success', True) ret = {'name': name, 'changes': {'return': runner_return}, 'result': success} ret['comment'] = "Runner function '{0}' {1}.".format( name, 'executed' if success else 'failed', ) ret['__orchestration__'] = True if 'jid' in out: ret['__jid__'] = out['jid'] return ret
[ "def", "runner", "(", "name", ",", "*", "*", "kwargs", ")", ":", "try", ":", "jid", "=", "__orchestration_jid__", "except", "NameError", ":", "log", ".", "debug", "(", "'Unable to fire args event due to missing __orchestration_jid__'", ")", "jid", "=", "None", "...
Execute a runner module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the runner function asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon .. code-block:: yaml run-manage-up: salt.runner: - name: manage.up
[ "Execute", "a", "runner", "module", "on", "the", "master" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltmod.py#L751-L819
train
saltstack/salt
salt/states/saltmod.py
parallel_runners
def parallel_runners(name, runners, **kwargs): # pylint: disable=unused-argument ''' Executes multiple runner modules on the master in parallel. .. versionadded:: 2017.x.0 (Nitrogen) A separate thread is spawned for each runner. This state is intended to be used with the orchestrate runner in place of the ``saltmod.runner`` state when different tasks should be run in parallel. In general, Salt states are not safe when used concurrently, so ensure that they are used in a safe way (e.g. by only targeting separate minions in parallel tasks). name: name identifying this state. The name is provided as part of the output, but not used for anything else. runners: list of runners that should be run in parallel. Each element of the list has to be a dictionary. This dictionary's name entry stores the name of the runner function that shall be invoked. The optional kwarg entry stores a dictionary of named arguments that are passed to the runner function. .. code-block:: yaml parallel-state: salt.parallel_runners: - runners: my_runner_1: - name: state.orchestrate - kwarg: mods: orchestrate_state_1 my_runner_2: - name: state.orchestrate - kwarg: mods: orchestrate_state_2 ''' # For the sake of consistency, we treat a single string in the same way as # a key without a value. This allows something like # salt.parallel_runners: # - runners: # state.orchestrate # Obviously, this will only work if the specified runner does not need any # arguments. if isinstance(runners, six.string_types): runners = {runners: [{name: runners}]} # If the runners argument is not a string, it must be a dict. Everything # else is considered an error. if not isinstance(runners, dict): return { 'name': name, 'result': False, 'changes': {}, 'comment': 'The runners parameter must be a string or dict.' } # The configuration for each runner is given as a list of key-value pairs. # This is not very useful for what we want to do, but it is the typical # style used in Salt. For further processing, we convert each of these # lists to a dict. This also makes it easier to check whether a name has # been specified explicitly. for runner_id, runner_config in six.iteritems(runners): if runner_config is None: runner_config = {} else: runner_config = salt.utils.data.repack_dictlist(runner_config) if 'name' not in runner_config: runner_config['name'] = runner_id runners[runner_id] = runner_config try: jid = __orchestration_jid__ except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__') jid = None def call_runner(runner_config): return __salt__['saltutil.runner'](runner_config['name'], __orchestration_jid__=jid, __env__=__env__, full_return=True, **(runner_config.get('kwarg', {}))) try: outputs = _parallel_map(call_runner, list(six.itervalues(runners))) except salt.exceptions.SaltException as exc: return { 'name': name, 'result': False, 'success': False, 'changes': {}, 'comment': 'One of the runners raised an exception: {0}'.format( exc) } # We bundle the results of the runners with the IDs of the runners so that # we can easily identify which output belongs to which runner. At the same # time we exctract the actual return value of the runner (saltutil.runner # adds some extra information that is not interesting to us). outputs = { runner_id: out['return']for runner_id, out in six.moves.zip(six.iterkeys(runners), outputs) } # If each of the runners returned its output in the format compatible with # the 'highstate' outputter, we can leverage this fact when merging the # outputs. highstate_output = all( [out.get('outputter', '') == 'highstate' and 'data' in out for out in six.itervalues(outputs)] ) # The following helper function is used to extract changes from highstate # output. def extract_changes(obj): if not isinstance(obj, dict): return {} elif 'changes' in obj: if (isinstance(obj['changes'], dict) and obj['changes'].get('out', '') == 'highstate' and 'ret' in obj['changes']): return obj['changes']['ret'] else: return obj['changes'] else: found_changes = {} for key, value in six.iteritems(obj): change = extract_changes(value) if change: found_changes[key] = change return found_changes if highstate_output: failed_runners = [runner_id for runner_id, out in six.iteritems(outputs) if out['data'].get('retcode', 0) != 0] all_successful = not failed_runners if all_successful: comment = 'All runner functions executed successfully.' else: runner_comments = [ 'Runner {0} failed with return value:\n{1}'.format( runner_id, salt.output.out_format(outputs[runner_id], 'nested', __opts__, nested_indent=2) ) for runner_id in failed_runners ] comment = '\n'.join(runner_comments) changes = {} for runner_id, out in six.iteritems(outputs): runner_changes = extract_changes(out['data']) if runner_changes: changes[runner_id] = runner_changes else: failed_runners = [runner_id for runner_id, out in six.iteritems(outputs) if out.get('exit_code', 0) != 0] all_successful = not failed_runners if all_successful: comment = 'All runner functions executed successfully.' else: if len(failed_runners) == 1: comment = 'Runner {0} failed.'.format(failed_runners[0]) else: comment =\ 'Runners {0} failed.'.format(', '.join(failed_runners)) changes = {'ret': { runner_id: out for runner_id, out in six.iteritems(outputs) }} ret = { 'name': name, 'result': all_successful, 'changes': changes, 'comment': comment } # The 'runner' function includes out['jid'] as '__jid__' in the returned # dict, but we cannot do this here because we have more than one JID if # we have more than one runner. return ret
python
def parallel_runners(name, runners, **kwargs): # pylint: disable=unused-argument ''' Executes multiple runner modules on the master in parallel. .. versionadded:: 2017.x.0 (Nitrogen) A separate thread is spawned for each runner. This state is intended to be used with the orchestrate runner in place of the ``saltmod.runner`` state when different tasks should be run in parallel. In general, Salt states are not safe when used concurrently, so ensure that they are used in a safe way (e.g. by only targeting separate minions in parallel tasks). name: name identifying this state. The name is provided as part of the output, but not used for anything else. runners: list of runners that should be run in parallel. Each element of the list has to be a dictionary. This dictionary's name entry stores the name of the runner function that shall be invoked. The optional kwarg entry stores a dictionary of named arguments that are passed to the runner function. .. code-block:: yaml parallel-state: salt.parallel_runners: - runners: my_runner_1: - name: state.orchestrate - kwarg: mods: orchestrate_state_1 my_runner_2: - name: state.orchestrate - kwarg: mods: orchestrate_state_2 ''' # For the sake of consistency, we treat a single string in the same way as # a key without a value. This allows something like # salt.parallel_runners: # - runners: # state.orchestrate # Obviously, this will only work if the specified runner does not need any # arguments. if isinstance(runners, six.string_types): runners = {runners: [{name: runners}]} # If the runners argument is not a string, it must be a dict. Everything # else is considered an error. if not isinstance(runners, dict): return { 'name': name, 'result': False, 'changes': {}, 'comment': 'The runners parameter must be a string or dict.' } # The configuration for each runner is given as a list of key-value pairs. # This is not very useful for what we want to do, but it is the typical # style used in Salt. For further processing, we convert each of these # lists to a dict. This also makes it easier to check whether a name has # been specified explicitly. for runner_id, runner_config in six.iteritems(runners): if runner_config is None: runner_config = {} else: runner_config = salt.utils.data.repack_dictlist(runner_config) if 'name' not in runner_config: runner_config['name'] = runner_id runners[runner_id] = runner_config try: jid = __orchestration_jid__ except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__') jid = None def call_runner(runner_config): return __salt__['saltutil.runner'](runner_config['name'], __orchestration_jid__=jid, __env__=__env__, full_return=True, **(runner_config.get('kwarg', {}))) try: outputs = _parallel_map(call_runner, list(six.itervalues(runners))) except salt.exceptions.SaltException as exc: return { 'name': name, 'result': False, 'success': False, 'changes': {}, 'comment': 'One of the runners raised an exception: {0}'.format( exc) } # We bundle the results of the runners with the IDs of the runners so that # we can easily identify which output belongs to which runner. At the same # time we exctract the actual return value of the runner (saltutil.runner # adds some extra information that is not interesting to us). outputs = { runner_id: out['return']for runner_id, out in six.moves.zip(six.iterkeys(runners), outputs) } # If each of the runners returned its output in the format compatible with # the 'highstate' outputter, we can leverage this fact when merging the # outputs. highstate_output = all( [out.get('outputter', '') == 'highstate' and 'data' in out for out in six.itervalues(outputs)] ) # The following helper function is used to extract changes from highstate # output. def extract_changes(obj): if not isinstance(obj, dict): return {} elif 'changes' in obj: if (isinstance(obj['changes'], dict) and obj['changes'].get('out', '') == 'highstate' and 'ret' in obj['changes']): return obj['changes']['ret'] else: return obj['changes'] else: found_changes = {} for key, value in six.iteritems(obj): change = extract_changes(value) if change: found_changes[key] = change return found_changes if highstate_output: failed_runners = [runner_id for runner_id, out in six.iteritems(outputs) if out['data'].get('retcode', 0) != 0] all_successful = not failed_runners if all_successful: comment = 'All runner functions executed successfully.' else: runner_comments = [ 'Runner {0} failed with return value:\n{1}'.format( runner_id, salt.output.out_format(outputs[runner_id], 'nested', __opts__, nested_indent=2) ) for runner_id in failed_runners ] comment = '\n'.join(runner_comments) changes = {} for runner_id, out in six.iteritems(outputs): runner_changes = extract_changes(out['data']) if runner_changes: changes[runner_id] = runner_changes else: failed_runners = [runner_id for runner_id, out in six.iteritems(outputs) if out.get('exit_code', 0) != 0] all_successful = not failed_runners if all_successful: comment = 'All runner functions executed successfully.' else: if len(failed_runners) == 1: comment = 'Runner {0} failed.'.format(failed_runners[0]) else: comment =\ 'Runners {0} failed.'.format(', '.join(failed_runners)) changes = {'ret': { runner_id: out for runner_id, out in six.iteritems(outputs) }} ret = { 'name': name, 'result': all_successful, 'changes': changes, 'comment': comment } # The 'runner' function includes out['jid'] as '__jid__' in the returned # dict, but we cannot do this here because we have more than one JID if # we have more than one runner. return ret
[ "def", "parallel_runners", "(", "name", ",", "runners", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "# For the sake of consistency, we treat a single string in the same way as", "# a key without a value. This allows something like", "# salt.parallel_runn...
Executes multiple runner modules on the master in parallel. .. versionadded:: 2017.x.0 (Nitrogen) A separate thread is spawned for each runner. This state is intended to be used with the orchestrate runner in place of the ``saltmod.runner`` state when different tasks should be run in parallel. In general, Salt states are not safe when used concurrently, so ensure that they are used in a safe way (e.g. by only targeting separate minions in parallel tasks). name: name identifying this state. The name is provided as part of the output, but not used for anything else. runners: list of runners that should be run in parallel. Each element of the list has to be a dictionary. This dictionary's name entry stores the name of the runner function that shall be invoked. The optional kwarg entry stores a dictionary of named arguments that are passed to the runner function. .. code-block:: yaml parallel-state: salt.parallel_runners: - runners: my_runner_1: - name: state.orchestrate - kwarg: mods: orchestrate_state_1 my_runner_2: - name: state.orchestrate - kwarg: mods: orchestrate_state_2
[ "Executes", "multiple", "runner", "modules", "on", "the", "master", "in", "parallel", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltmod.py#L822-L1003
train
saltstack/salt
salt/states/saltmod.py
wheel
def wheel(name, **kwargs): ''' Execute a wheel module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the wheel function asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon .. code-block:: yaml accept_minion_key: salt.wheel: - name: key.accept - match: frank ''' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} try: jid = __orchestration_jid__ except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__' ) jid = None if __opts__.get('test', False): ret['result'] = None, ret['changes'] = {} ret['comment'] = "Wheel function '{0}' would be executed.".format(name) return ret out = __salt__['saltutil.wheel'](name, __orchestration_jid__=jid, __env__=__env__, **kwargs) if kwargs.get('asynchronous'): ret['__jid__'] = ret.get('jid') ret['changes'] = out if int(out.get('jid', 0)) > 0: ret['result'] = True ret['comment'] = 'wheel submitted successfully.' else: ret['result'] = False ret['comment'] = 'wheel failed to run.' return ret wheel_return = out.get('return') if isinstance(wheel_return, dict) and 'Error' in wheel_return: out['success'] = False success = out.get('success', True) ret = {'name': name, 'changes': {'return': wheel_return}, 'result': success} ret['comment'] = "Wheel function '{0}' {1}.".format( name, 'executed' if success else 'failed', ) ret['__orchestration__'] = True if 'jid' in out: ret['__jid__'] = out['jid'] return ret
python
def wheel(name, **kwargs): ''' Execute a wheel module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the wheel function asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon .. code-block:: yaml accept_minion_key: salt.wheel: - name: key.accept - match: frank ''' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} try: jid = __orchestration_jid__ except NameError: log.debug( 'Unable to fire args event due to missing __orchestration_jid__' ) jid = None if __opts__.get('test', False): ret['result'] = None, ret['changes'] = {} ret['comment'] = "Wheel function '{0}' would be executed.".format(name) return ret out = __salt__['saltutil.wheel'](name, __orchestration_jid__=jid, __env__=__env__, **kwargs) if kwargs.get('asynchronous'): ret['__jid__'] = ret.get('jid') ret['changes'] = out if int(out.get('jid', 0)) > 0: ret['result'] = True ret['comment'] = 'wheel submitted successfully.' else: ret['result'] = False ret['comment'] = 'wheel failed to run.' return ret wheel_return = out.get('return') if isinstance(wheel_return, dict) and 'Error' in wheel_return: out['success'] = False success = out.get('success', True) ret = {'name': name, 'changes': {'return': wheel_return}, 'result': success} ret['comment'] = "Wheel function '{0}' {1}.".format( name, 'executed' if success else 'failed', ) ret['__orchestration__'] = True if 'jid' in out: ret['__jid__'] = out['jid'] return ret
[ "def", "wheel", "(", "name", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "try", ":", "jid", "=", "__orchestration_jid__...
Execute a wheel module on the master .. versionadded:: 2014.7.0 name The name of the function to run kwargs Any keyword arguments to pass to the wheel function asynchronous Run the salt command but don't wait for a reply. .. versionadded:: neon .. code-block:: yaml accept_minion_key: salt.wheel: - name: key.accept - match: frank
[ "Execute", "a", "wheel", "module", "on", "the", "master" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltmod.py#L1006-L1079
train
saltstack/salt
salt/modules/slack_notify.py
list_rooms
def list_rooms(api_key=None): ''' List all Slack rooms. :param api_key: The Slack admin api key. :return: The room list. CLI Example: .. code-block:: bash salt '*' slack.list_rooms salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' if not api_key: api_key = _get_api_key() return salt.utils.slack.query(function='rooms', api_key=api_key, opts=__opts__)
python
def list_rooms(api_key=None): ''' List all Slack rooms. :param api_key: The Slack admin api key. :return: The room list. CLI Example: .. code-block:: bash salt '*' slack.list_rooms salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' if not api_key: api_key = _get_api_key() return salt.utils.slack.query(function='rooms', api_key=api_key, opts=__opts__)
[ "def", "list_rooms", "(", "api_key", "=", "None", ")", ":", "if", "not", "api_key", ":", "api_key", "=", "_get_api_key", "(", ")", "return", "salt", ".", "utils", ".", "slack", ".", "query", "(", "function", "=", "'rooms'", ",", "api_key", "=", "api_ke...
List all Slack rooms. :param api_key: The Slack admin api key. :return: The room list. CLI Example: .. code-block:: bash salt '*' slack.list_rooms salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15
[ "List", "all", "Slack", "rooms", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slack_notify.py#L69-L88
train
saltstack/salt
salt/modules/slack_notify.py
find_room
def find_room(name, api_key=None): ''' Find a room by name and return it. :param name: The room name. :param api_key: The Slack admin api key. :return: The room object. CLI Example: .. code-block:: bash salt '*' slack.find_room name="random" salt '*' slack.find_room name="random" api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' if not api_key: api_key = _get_api_key() # search results don't include the name of the # channel with a hash, if the passed channel name # has a hash we remove it. if name.startswith('#'): name = name[1:] ret = list_rooms(api_key) if ret['res']: rooms = ret['message'] if rooms: for room in range(0, len(rooms)): if rooms[room]['name'] == name: return rooms[room] return False
python
def find_room(name, api_key=None): ''' Find a room by name and return it. :param name: The room name. :param api_key: The Slack admin api key. :return: The room object. CLI Example: .. code-block:: bash salt '*' slack.find_room name="random" salt '*' slack.find_room name="random" api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' if not api_key: api_key = _get_api_key() # search results don't include the name of the # channel with a hash, if the passed channel name # has a hash we remove it. if name.startswith('#'): name = name[1:] ret = list_rooms(api_key) if ret['res']: rooms = ret['message'] if rooms: for room in range(0, len(rooms)): if rooms[room]['name'] == name: return rooms[room] return False
[ "def", "find_room", "(", "name", ",", "api_key", "=", "None", ")", ":", "if", "not", "api_key", ":", "api_key", "=", "_get_api_key", "(", ")", "# search results don't include the name of the", "# channel with a hash, if the passed channel name", "# has a hash we remove it."...
Find a room by name and return it. :param name: The room name. :param api_key: The Slack admin api key. :return: The room object. CLI Example: .. code-block:: bash salt '*' slack.find_room name="random" salt '*' slack.find_room name="random" api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15
[ "Find", "a", "room", "by", "name", "and", "return", "it", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slack_notify.py#L113-L144
train
saltstack/salt
salt/modules/slack_notify.py
find_user
def find_user(name, api_key=None): ''' Find a user by name and return it. :param name: The user name. :param api_key: The Slack admin api key. :return: The user object. CLI Example: .. code-block:: bash salt '*' slack.find_user name="ThomasHatch" salt '*' slack.find_user name="ThomasHatch" api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' if not api_key: api_key = _get_api_key() ret = list_users(api_key) if ret['res']: users = ret['message'] if users: for user in range(0, len(users)): if users[user]['name'] == name: return users[user] return False
python
def find_user(name, api_key=None): ''' Find a user by name and return it. :param name: The user name. :param api_key: The Slack admin api key. :return: The user object. CLI Example: .. code-block:: bash salt '*' slack.find_user name="ThomasHatch" salt '*' slack.find_user name="ThomasHatch" api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' if not api_key: api_key = _get_api_key() ret = list_users(api_key) if ret['res']: users = ret['message'] if users: for user in range(0, len(users)): if users[user]['name'] == name: return users[user] return False
[ "def", "find_user", "(", "name", ",", "api_key", "=", "None", ")", ":", "if", "not", "api_key", ":", "api_key", "=", "_get_api_key", "(", ")", "ret", "=", "list_users", "(", "api_key", ")", "if", "ret", "[", "'res'", "]", ":", "users", "=", "ret", ...
Find a user by name and return it. :param name: The user name. :param api_key: The Slack admin api key. :return: The user object. CLI Example: .. code-block:: bash salt '*' slack.find_user name="ThomasHatch" salt '*' slack.find_user name="ThomasHatch" api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15
[ "Find", "a", "user", "by", "name", "and", "return", "it", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slack_notify.py#L147-L173
train
saltstack/salt
salt/modules/slack_notify.py
post_message
def post_message(channel, message, from_name, api_key=None, icon=None): ''' Send a message to a Slack channel. :param channel: The channel name, either will work. :param message: The message to send to the Slack channel. :param from_name: Specify who the message is from. :param api_key: The Slack api key, if not specified in the configuration. :param icon: URL to an image to use as the icon for this message :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' slack.post_message channel="Development Room" message="Build is done" from_name="Build Server" ''' if not api_key: api_key = _get_api_key() if not channel: log.error('channel is a required option.') # channel must start with a hash or an @ (direct-message channels) if not channel.startswith('#') and not channel.startswith('@'): log.warning('Channel name must start with a hash or @. ' 'Prepending a hash and using "#%s" as ' 'channel name instead of %s', channel, channel) channel = '#{0}'.format(channel) if not from_name: log.error('from_name is a required option.') if not message: log.error('message is a required option.') if not from_name: log.error('from_name is a required option.') parameters = { 'channel': channel, 'username': from_name, 'text': message } if icon is not None: parameters['icon_url'] = icon # Slack wants the body on POST to be urlencoded. result = salt.utils.slack.query(function='message', api_key=api_key, method='POST', header_dict={'Content-Type': 'application/x-www-form-urlencoded'}, data=_urlencode(parameters), opts=__opts__) if result['res']: return True else: return result
python
def post_message(channel, message, from_name, api_key=None, icon=None): ''' Send a message to a Slack channel. :param channel: The channel name, either will work. :param message: The message to send to the Slack channel. :param from_name: Specify who the message is from. :param api_key: The Slack api key, if not specified in the configuration. :param icon: URL to an image to use as the icon for this message :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' slack.post_message channel="Development Room" message="Build is done" from_name="Build Server" ''' if not api_key: api_key = _get_api_key() if not channel: log.error('channel is a required option.') # channel must start with a hash or an @ (direct-message channels) if not channel.startswith('#') and not channel.startswith('@'): log.warning('Channel name must start with a hash or @. ' 'Prepending a hash and using "#%s" as ' 'channel name instead of %s', channel, channel) channel = '#{0}'.format(channel) if not from_name: log.error('from_name is a required option.') if not message: log.error('message is a required option.') if not from_name: log.error('from_name is a required option.') parameters = { 'channel': channel, 'username': from_name, 'text': message } if icon is not None: parameters['icon_url'] = icon # Slack wants the body on POST to be urlencoded. result = salt.utils.slack.query(function='message', api_key=api_key, method='POST', header_dict={'Content-Type': 'application/x-www-form-urlencoded'}, data=_urlencode(parameters), opts=__opts__) if result['res']: return True else: return result
[ "def", "post_message", "(", "channel", ",", "message", ",", "from_name", ",", "api_key", "=", "None", ",", "icon", "=", "None", ")", ":", "if", "not", "api_key", ":", "api_key", "=", "_get_api_key", "(", ")", "if", "not", "channel", ":", "log", ".", ...
Send a message to a Slack channel. :param channel: The channel name, either will work. :param message: The message to send to the Slack channel. :param from_name: Specify who the message is from. :param api_key: The Slack api key, if not specified in the configuration. :param icon: URL to an image to use as the icon for this message :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' slack.post_message channel="Development Room" message="Build is done" from_name="Build Server"
[ "Send", "a", "message", "to", "a", "Slack", "channel", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slack_notify.py#L176-L241
train
saltstack/salt
salt/modules/slack_notify.py
call_hook
def call_hook(message, attachment=None, color='good', short=False, identifier=None, channel=None, username=None, icon_emoji=None): ''' Send message to Slack incoming webhook. :param message: The topic of message. :param attachment: The message to send to the Slacke WebHook. :param color: The color of border of left side :param short: An optional flag indicating whether the value is short enough to be displayed side-by-side with other values. :param identifier: The identifier of WebHook. :param channel: The channel to use instead of the WebHook default. :param username: Username to use instead of WebHook default. :param icon_emoji: Icon to use instead of WebHook default. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' slack.call_hook message='Hello, from SaltStack' ''' base_url = 'https://hooks.slack.com/services/' if not identifier: identifier = _get_hook_id() url = _urljoin(base_url, identifier) if not message: log.error('message is required option') if attachment: payload = { 'attachments': [ { 'fallback': message, 'color': color, 'pretext': message, 'fields': [ { "value": attachment, "short": short, } ] } ] } else: payload = { 'text': message, } if channel: payload['channel'] = channel if username: payload['username'] = username if icon_emoji: payload['icon_emoji'] = icon_emoji data = _urlencode( { 'payload': salt.utils.json.dumps(payload) } ) result = salt.utils.http.query(url, method='POST', data=data, status=True) if result['status'] <= 201: return True else: return { 'res': False, 'message': result.get('body', result['status']) }
python
def call_hook(message, attachment=None, color='good', short=False, identifier=None, channel=None, username=None, icon_emoji=None): ''' Send message to Slack incoming webhook. :param message: The topic of message. :param attachment: The message to send to the Slacke WebHook. :param color: The color of border of left side :param short: An optional flag indicating whether the value is short enough to be displayed side-by-side with other values. :param identifier: The identifier of WebHook. :param channel: The channel to use instead of the WebHook default. :param username: Username to use instead of WebHook default. :param icon_emoji: Icon to use instead of WebHook default. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' slack.call_hook message='Hello, from SaltStack' ''' base_url = 'https://hooks.slack.com/services/' if not identifier: identifier = _get_hook_id() url = _urljoin(base_url, identifier) if not message: log.error('message is required option') if attachment: payload = { 'attachments': [ { 'fallback': message, 'color': color, 'pretext': message, 'fields': [ { "value": attachment, "short": short, } ] } ] } else: payload = { 'text': message, } if channel: payload['channel'] = channel if username: payload['username'] = username if icon_emoji: payload['icon_emoji'] = icon_emoji data = _urlencode( { 'payload': salt.utils.json.dumps(payload) } ) result = salt.utils.http.query(url, method='POST', data=data, status=True) if result['status'] <= 201: return True else: return { 'res': False, 'message': result.get('body', result['status']) }
[ "def", "call_hook", "(", "message", ",", "attachment", "=", "None", ",", "color", "=", "'good'", ",", "short", "=", "False", ",", "identifier", "=", "None", ",", "channel", "=", "None", ",", "username", "=", "None", ",", "icon_emoji", "=", "None", ")",...
Send message to Slack incoming webhook. :param message: The topic of message. :param attachment: The message to send to the Slacke WebHook. :param color: The color of border of left side :param short: An optional flag indicating whether the value is short enough to be displayed side-by-side with other values. :param identifier: The identifier of WebHook. :param channel: The channel to use instead of the WebHook default. :param username: Username to use instead of WebHook default. :param icon_emoji: Icon to use instead of WebHook default. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt '*' slack.call_hook message='Hello, from SaltStack'
[ "Send", "message", "to", "Slack", "incoming", "webhook", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slack_notify.py#L244-L325
train
saltstack/salt
salt/modules/groupadd.py
add
def add(name, gid=None, system=False, root=None): ''' Add the specified group name Name of the new group gid Use GID for the new group system Create a system account root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.add foo 3456 ''' cmd = ['groupadd'] if gid: cmd.append('-g {0}'.format(gid)) if system and __grains__['kernel'] != 'OpenBSD': cmd.append('-r') if root is not None: cmd.extend(('-R', root)) cmd.append(name) ret = __salt__['cmd.run_all'](cmd, python_shell=False) return not ret['retcode']
python
def add(name, gid=None, system=False, root=None): ''' Add the specified group name Name of the new group gid Use GID for the new group system Create a system account root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.add foo 3456 ''' cmd = ['groupadd'] if gid: cmd.append('-g {0}'.format(gid)) if system and __grains__['kernel'] != 'OpenBSD': cmd.append('-r') if root is not None: cmd.extend(('-R', root)) cmd.append(name) ret = __salt__['cmd.run_all'](cmd, python_shell=False) return not ret['retcode']
[ "def", "add", "(", "name", ",", "gid", "=", "None", ",", "system", "=", "False", ",", "root", "=", "None", ")", ":", "cmd", "=", "[", "'groupadd'", "]", "if", "gid", ":", "cmd", ".", "append", "(", "'-g {0}'", ".", "format", "(", "gid", ")", ")...
Add the specified group name Name of the new group gid Use GID for the new group system Create a system account root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.add foo 3456
[ "Add", "the", "specified", "group" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L43-L78
train
saltstack/salt
salt/modules/groupadd.py
delete
def delete(name, root=None): ''' Remove the named group name Name group to delete root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.delete foo ''' cmd = ['groupdel'] if root is not None: cmd.extend(('-R', root)) cmd.append(name) ret = __salt__['cmd.run_all'](cmd, python_shell=False) return not ret['retcode']
python
def delete(name, root=None): ''' Remove the named group name Name group to delete root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.delete foo ''' cmd = ['groupdel'] if root is not None: cmd.extend(('-R', root)) cmd.append(name) ret = __salt__['cmd.run_all'](cmd, python_shell=False) return not ret['retcode']
[ "def", "delete", "(", "name", ",", "root", "=", "None", ")", ":", "cmd", "=", "[", "'groupdel'", "]", "if", "root", "is", "not", "None", ":", "cmd", ".", "extend", "(", "(", "'-R'", ",", "root", ")", ")", "cmd", ".", "append", "(", "name", ")",...
Remove the named group name Name group to delete root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.delete foo
[ "Remove", "the", "named", "group" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L81-L106
train
saltstack/salt
salt/modules/groupadd.py
info
def info(name, root=None): ''' Return information about a group name Name of the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.info foo ''' if root is not None: getgrnam = functools.partial(_getgrnam, root=root) else: getgrnam = functools.partial(grp.getgrnam) try: grinfo = getgrnam(name) except KeyError: return {} else: return _format_info(grinfo)
python
def info(name, root=None): ''' Return information about a group name Name of the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.info foo ''' if root is not None: getgrnam = functools.partial(_getgrnam, root=root) else: getgrnam = functools.partial(grp.getgrnam) try: grinfo = getgrnam(name) except KeyError: return {} else: return _format_info(grinfo)
[ "def", "info", "(", "name", ",", "root", "=", "None", ")", ":", "if", "root", "is", "not", "None", ":", "getgrnam", "=", "functools", ".", "partial", "(", "_getgrnam", ",", "root", "=", "root", ")", "else", ":", "getgrnam", "=", "functools", ".", "...
Return information about a group name Name of the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.info foo
[ "Return", "information", "about", "a", "group" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L109-L135
train
saltstack/salt
salt/modules/groupadd.py
getent
def getent(refresh=False, root=None): ''' Return info on all groups refresh Force a refresh of group information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.getent ''' if 'group.getent' in __context__ and not refresh: return __context__['group.getent'] ret = [] if root is not None: getgrall = functools.partial(_getgrall, root=root) else: getgrall = functools.partial(grp.getgrall) for grinfo in getgrall(): ret.append(_format_info(grinfo)) __context__['group.getent'] = ret return ret
python
def getent(refresh=False, root=None): ''' Return info on all groups refresh Force a refresh of group information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.getent ''' if 'group.getent' in __context__ and not refresh: return __context__['group.getent'] ret = [] if root is not None: getgrall = functools.partial(_getgrall, root=root) else: getgrall = functools.partial(grp.getgrall) for grinfo in getgrall(): ret.append(_format_info(grinfo)) __context__['group.getent'] = ret return ret
[ "def", "getent", "(", "refresh", "=", "False", ",", "root", "=", "None", ")", ":", "if", "'group.getent'", "in", "__context__", "and", "not", "refresh", ":", "return", "__context__", "[", "'group.getent'", "]", "ret", "=", "[", "]", "if", "root", "is", ...
Return info on all groups refresh Force a refresh of group information root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.getent
[ "Return", "info", "on", "all", "groups" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L148-L176
train
saltstack/salt
salt/modules/groupadd.py
_chattrib
def _chattrib(name, key, value, param, root=None): ''' Change an attribute for a named user ''' pre_info = info(name, root=root) if not pre_info: return False if value == pre_info[key]: return True cmd = ['groupmod'] if root is not None: cmd.extend(('-R', root)) cmd.extend((param, value, name)) __salt__['cmd.run'](cmd, python_shell=False) return info(name, root=root).get(key) == value
python
def _chattrib(name, key, value, param, root=None): ''' Change an attribute for a named user ''' pre_info = info(name, root=root) if not pre_info: return False if value == pre_info[key]: return True cmd = ['groupmod'] if root is not None: cmd.extend(('-R', root)) cmd.extend((param, value, name)) __salt__['cmd.run'](cmd, python_shell=False) return info(name, root=root).get(key) == value
[ "def", "_chattrib", "(", "name", ",", "key", ",", "value", ",", "param", ",", "root", "=", "None", ")", ":", "pre_info", "=", "info", "(", "name", ",", "root", "=", "root", ")", "if", "not", "pre_info", ":", "return", "False", "if", "value", "==", ...
Change an attribute for a named user
[ "Change", "an", "attribute", "for", "a", "named", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L179-L198
train
saltstack/salt
salt/modules/groupadd.py
adduser
def adduser(name, username, root=None): ''' Add a user in the group. name Name of the group to modify username Username to add to the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.adduser foo bar Verifies if a valid username 'bar' as a member of an existing group 'foo', if not then adds it. ''' on_redhat_5 = __grains__.get('os_family') == 'RedHat' and __grains__.get('osmajorrelease') == '5' on_suse_11 = __grains__.get('os_family') == 'Suse' and __grains__.get('osmajorrelease') == '11' if __grains__['kernel'] == 'Linux': if on_redhat_5: cmd = ['gpasswd', '-a', username, name] elif on_suse_11: cmd = ['usermod', '-A', name, username] else: cmd = ['gpasswd', '--add', username, name] if root is not None: cmd.extend(('--root', root)) else: cmd = ['usermod', '-G', name, username] if root is not None: cmd.extend(('-R', root)) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) return not retcode
python
def adduser(name, username, root=None): ''' Add a user in the group. name Name of the group to modify username Username to add to the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.adduser foo bar Verifies if a valid username 'bar' as a member of an existing group 'foo', if not then adds it. ''' on_redhat_5 = __grains__.get('os_family') == 'RedHat' and __grains__.get('osmajorrelease') == '5' on_suse_11 = __grains__.get('os_family') == 'Suse' and __grains__.get('osmajorrelease') == '11' if __grains__['kernel'] == 'Linux': if on_redhat_5: cmd = ['gpasswd', '-a', username, name] elif on_suse_11: cmd = ['usermod', '-A', name, username] else: cmd = ['gpasswd', '--add', username, name] if root is not None: cmd.extend(('--root', root)) else: cmd = ['usermod', '-G', name, username] if root is not None: cmd.extend(('-R', root)) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) return not retcode
[ "def", "adduser", "(", "name", ",", "username", ",", "root", "=", "None", ")", ":", "on_redhat_5", "=", "__grains__", ".", "get", "(", "'os_family'", ")", "==", "'RedHat'", "and", "__grains__", ".", "get", "(", "'osmajorrelease'", ")", "==", "'5'", "on_s...
Add a user in the group. name Name of the group to modify username Username to add to the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.adduser foo bar Verifies if a valid username 'bar' as a member of an existing group 'foo', if not then adds it.
[ "Add", "a", "user", "in", "the", "group", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L223-L264
train
saltstack/salt
salt/modules/groupadd.py
deluser
def deluser(name, username, root=None): ''' Remove a user from the group. name Name of the group to modify username Username to delete from the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If group is not present then returns True. ''' on_redhat_5 = __grains__.get('os_family') == 'RedHat' and __grains__.get('osmajorrelease') == '5' on_suse_11 = __grains__.get('os_family') == 'Suse' and __grains__.get('osmajorrelease') == '11' grp_info = __salt__['group.info'](name) try: if username in grp_info['members']: if __grains__['kernel'] == 'Linux': if on_redhat_5: cmd = ['gpasswd', '-d', username, name] elif on_suse_11: cmd = ['usermod', '-R', name, username] else: cmd = ['gpasswd', '--del', username, name] if root is not None: cmd.extend(('--root', root)) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) elif __grains__['kernel'] == 'OpenBSD': out = __salt__['cmd.run_stdout']('id -Gn {0}'.format(username), python_shell=False) cmd = ['usermod', '-S'] cmd.append(','.join([g for g in out.split() if g != six.text_type(name)])) cmd.append('{0}'.format(username)) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) else: log.error('group.deluser is not yet supported on this platform') return False return not retcode else: return True except Exception: return True
python
def deluser(name, username, root=None): ''' Remove a user from the group. name Name of the group to modify username Username to delete from the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If group is not present then returns True. ''' on_redhat_5 = __grains__.get('os_family') == 'RedHat' and __grains__.get('osmajorrelease') == '5' on_suse_11 = __grains__.get('os_family') == 'Suse' and __grains__.get('osmajorrelease') == '11' grp_info = __salt__['group.info'](name) try: if username in grp_info['members']: if __grains__['kernel'] == 'Linux': if on_redhat_5: cmd = ['gpasswd', '-d', username, name] elif on_suse_11: cmd = ['usermod', '-R', name, username] else: cmd = ['gpasswd', '--del', username, name] if root is not None: cmd.extend(('--root', root)) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) elif __grains__['kernel'] == 'OpenBSD': out = __salt__['cmd.run_stdout']('id -Gn {0}'.format(username), python_shell=False) cmd = ['usermod', '-S'] cmd.append(','.join([g for g in out.split() if g != six.text_type(name)])) cmd.append('{0}'.format(username)) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) else: log.error('group.deluser is not yet supported on this platform') return False return not retcode else: return True except Exception: return True
[ "def", "deluser", "(", "name", ",", "username", ",", "root", "=", "None", ")", ":", "on_redhat_5", "=", "__grains__", ".", "get", "(", "'os_family'", ")", "==", "'RedHat'", "and", "__grains__", ".", "get", "(", "'osmajorrelease'", ")", "==", "'5'", "on_s...
Remove a user from the group. name Name of the group to modify username Username to delete from the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If group is not present then returns True.
[ "Remove", "a", "user", "from", "the", "group", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L267-L319
train
saltstack/salt
salt/modules/groupadd.py
members
def members(name, members_list, root=None): ''' Replaces members of the group with a provided list. name Name of the group to modify members_list Username list to set into the group root Directory to chroot into CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,... ''' on_redhat_5 = __grains__.get('os_family') == 'RedHat' and __grains__.get('osmajorrelease') == '5' on_suse_11 = __grains__.get('os_family') == 'Suse' and __grains__.get('osmajorrelease') == '11' if __grains__['kernel'] == 'Linux': if on_redhat_5: cmd = ['gpasswd', '-M', members_list, name] elif on_suse_11: for old_member in __salt__['group.info'](name).get('members'): __salt__['cmd.run']('groupmod -R {0} {1}'.format(old_member, name), python_shell=False) cmd = ['groupmod', '-A', members_list, name] else: cmd = ['gpasswd', '--members', members_list, name] if root is not None: cmd.extend(('--root', root)) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) elif __grains__['kernel'] == 'OpenBSD': retcode = 1 grp_info = __salt__['group.info'](name) if grp_info and name in grp_info['name']: __salt__['cmd.run']('groupdel {0}'.format(name), python_shell=False) __salt__['cmd.run']('groupadd -g {0} {1}'.format( grp_info['gid'], name), python_shell=False) for user in members_list.split(","): if user: retcode = __salt__['cmd.retcode']( ['usermod', '-G', name, user], python_shell=False) if not retcode == 0: break # provided list is '': users previously deleted from group else: retcode = 0 else: log.error('group.members is not yet supported on this platform') return False return not retcode
python
def members(name, members_list, root=None): ''' Replaces members of the group with a provided list. name Name of the group to modify members_list Username list to set into the group root Directory to chroot into CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,... ''' on_redhat_5 = __grains__.get('os_family') == 'RedHat' and __grains__.get('osmajorrelease') == '5' on_suse_11 = __grains__.get('os_family') == 'Suse' and __grains__.get('osmajorrelease') == '11' if __grains__['kernel'] == 'Linux': if on_redhat_5: cmd = ['gpasswd', '-M', members_list, name] elif on_suse_11: for old_member in __salt__['group.info'](name).get('members'): __salt__['cmd.run']('groupmod -R {0} {1}'.format(old_member, name), python_shell=False) cmd = ['groupmod', '-A', members_list, name] else: cmd = ['gpasswd', '--members', members_list, name] if root is not None: cmd.extend(('--root', root)) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) elif __grains__['kernel'] == 'OpenBSD': retcode = 1 grp_info = __salt__['group.info'](name) if grp_info and name in grp_info['name']: __salt__['cmd.run']('groupdel {0}'.format(name), python_shell=False) __salt__['cmd.run']('groupadd -g {0} {1}'.format( grp_info['gid'], name), python_shell=False) for user in members_list.split(","): if user: retcode = __salt__['cmd.retcode']( ['usermod', '-G', name, user], python_shell=False) if not retcode == 0: break # provided list is '': users previously deleted from group else: retcode = 0 else: log.error('group.members is not yet supported on this platform') return False return not retcode
[ "def", "members", "(", "name", ",", "members_list", ",", "root", "=", "None", ")", ":", "on_redhat_5", "=", "__grains__", ".", "get", "(", "'os_family'", ")", "==", "'RedHat'", "and", "__grains__", ".", "get", "(", "'osmajorrelease'", ")", "==", "'5'", "...
Replaces members of the group with a provided list. name Name of the group to modify members_list Username list to set into the group root Directory to chroot into CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,...
[ "Replaces", "members", "of", "the", "group", "with", "a", "provided", "list", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L322-L379
train
saltstack/salt
salt/modules/groupadd.py
_getgrnam
def _getgrnam(name, root=None): ''' Alternative implementation for getgrnam, that use only /etc/group ''' root = root or '/' passwd = os.path.join(root, 'etc/group') with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(':') if len(comps) < 4: log.debug('Ignoring group line: %s', line) continue if comps[0] == name: # Generate a getpwnam compatible output comps[2] = int(comps[2]) comps[3] = comps[3].split(',') if comps[3] else [] return grp.struct_group(comps) raise KeyError('getgrnam(): name not found: {}'.format(name))
python
def _getgrnam(name, root=None): ''' Alternative implementation for getgrnam, that use only /etc/group ''' root = root or '/' passwd = os.path.join(root, 'etc/group') with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(':') if len(comps) < 4: log.debug('Ignoring group line: %s', line) continue if comps[0] == name: # Generate a getpwnam compatible output comps[2] = int(comps[2]) comps[3] = comps[3].split(',') if comps[3] else [] return grp.struct_group(comps) raise KeyError('getgrnam(): name not found: {}'.format(name))
[ "def", "_getgrnam", "(", "name", ",", "root", "=", "None", ")", ":", "root", "=", "root", "or", "'/'", "passwd", "=", "os", ".", "path", ".", "join", "(", "root", ",", "'etc/group'", ")", "with", "salt", ".", "utils", ".", "files", ".", "fopen", ...
Alternative implementation for getgrnam, that use only /etc/group
[ "Alternative", "implementation", "for", "getgrnam", "that", "use", "only", "/", "etc", "/", "group" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/groupadd.py#L382-L400
train
saltstack/salt
salt/modules/nagios.py
_execute_cmd
def _execute_cmd(plugin, args='', run_type='cmd.retcode'): ''' Execute nagios plugin if it's in the directory with salt command specified in run_type ''' data = {} all_plugins = list_plugins() if plugin in all_plugins: data = __salt__[run_type]( '{0}{1} {2}'.format(PLUGINDIR, plugin, args), python_shell=False) return data
python
def _execute_cmd(plugin, args='', run_type='cmd.retcode'): ''' Execute nagios plugin if it's in the directory with salt command specified in run_type ''' data = {} all_plugins = list_plugins() if plugin in all_plugins: data = __salt__[run_type]( '{0}{1} {2}'.format(PLUGINDIR, plugin, args), python_shell=False) return data
[ "def", "_execute_cmd", "(", "plugin", ",", "args", "=", "''", ",", "run_type", "=", "'cmd.retcode'", ")", ":", "data", "=", "{", "}", "all_plugins", "=", "list_plugins", "(", ")", "if", "plugin", "in", "all_plugins", ":", "data", "=", "__salt__", "[", ...
Execute nagios plugin if it's in the directory with salt command specified in run_type
[ "Execute", "nagios", "plugin", "if", "it", "s", "in", "the", "directory", "with", "salt", "command", "specified", "in", "run_type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios.py#L29-L41
train
saltstack/salt
salt/modules/nagios.py
_execute_pillar
def _execute_pillar(pillar_name, run_type): ''' Run one or more nagios plugins from pillar data and get the result of run_type The pillar have to be in this format: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - check_apt ------- ''' groups = __salt__['pillar.get'](pillar_name) data = {} for group in groups: data[group] = {} commands = groups[group] for command in commands: # Check if is a dict to get the arguments # in command if not set the arguments to empty string if isinstance(command, dict): plugin = next(six.iterkeys(command)) args = command[plugin] else: plugin = command args = '' command_key = _format_dict_key(args, plugin) data[group][command_key] = run_type(plugin, args) return data
python
def _execute_pillar(pillar_name, run_type): ''' Run one or more nagios plugins from pillar data and get the result of run_type The pillar have to be in this format: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - check_apt ------- ''' groups = __salt__['pillar.get'](pillar_name) data = {} for group in groups: data[group] = {} commands = groups[group] for command in commands: # Check if is a dict to get the arguments # in command if not set the arguments to empty string if isinstance(command, dict): plugin = next(six.iterkeys(command)) args = command[plugin] else: plugin = command args = '' command_key = _format_dict_key(args, plugin) data[group][command_key] = run_type(plugin, args) return data
[ "def", "_execute_pillar", "(", "pillar_name", ",", "run_type", ")", ":", "groups", "=", "__salt__", "[", "'pillar.get'", "]", "(", "pillar_name", ")", "data", "=", "{", "}", "for", "group", "in", "groups", ":", "data", "[", "group", "]", "=", "{", "}",...
Run one or more nagios plugins from pillar data and get the result of run_type The pillar have to be in this format: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - check_apt -------
[ "Run", "one", "or", "more", "nagios", "plugins", "from", "pillar", "data", "and", "get", "the", "result", "of", "run_type", "The", "pillar", "have", "to", "be", "in", "this", "format", ":", "------", "webserver", ":", "Ping_google", ":", "-", "check_icmp",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios.py#L44-L76
train
saltstack/salt
salt/modules/nagios.py
retcode
def retcode(plugin, args='', key_name=None): ''' Run one nagios plugin and return retcode of the execution ''' data = {} # Remove all the spaces, the key must not have any space if key_name is None: key_name = _format_dict_key(args, plugin) data[key_name] = {} status = _execute_cmd(plugin, args, 'cmd.retcode') data[key_name]['status'] = status return data
python
def retcode(plugin, args='', key_name=None): ''' Run one nagios plugin and return retcode of the execution ''' data = {} # Remove all the spaces, the key must not have any space if key_name is None: key_name = _format_dict_key(args, plugin) data[key_name] = {} status = _execute_cmd(plugin, args, 'cmd.retcode') data[key_name]['status'] = status return data
[ "def", "retcode", "(", "plugin", ",", "args", "=", "''", ",", "key_name", "=", "None", ")", ":", "data", "=", "{", "}", "# Remove all the spaces, the key must not have any space", "if", "key_name", "is", "None", ":", "key_name", "=", "_format_dict_key", "(", "...
Run one nagios plugin and return retcode of the execution
[ "Run", "one", "nagios", "plugin", "and", "return", "retcode", "of", "the", "execution" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios.py#L105-L120
train
saltstack/salt
salt/modules/nagios.py
retcode_pillar
def retcode_pillar(pillar_name): ''' Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - check_apt ------- webserver is the role to check, the next keys are the group and the items the check with the arguments if needed You must to group different checks(one o more) and always it will return the highest value of all the checks CLI Example: .. code-block:: bash salt '*' nagios.retcode webserver ''' groups = __salt__['pillar.get'](pillar_name) check = {} data = {} for group in groups: commands = groups[group] for command in commands: # Check if is a dict to get the arguments # in command if not set the arguments to empty string if isinstance(command, dict): plugin = next(six.iterkeys(command)) args = command[plugin] else: plugin = command args = '' check.update(retcode(plugin, args, group)) current_value = 0 new_value = int(check[group]['status']) if group in data: current_value = int(data[group]['status']) if (new_value > current_value) or (group not in data): if group not in data: data[group] = {} data[group]['status'] = new_value return data
python
def retcode_pillar(pillar_name): ''' Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - check_apt ------- webserver is the role to check, the next keys are the group and the items the check with the arguments if needed You must to group different checks(one o more) and always it will return the highest value of all the checks CLI Example: .. code-block:: bash salt '*' nagios.retcode webserver ''' groups = __salt__['pillar.get'](pillar_name) check = {} data = {} for group in groups: commands = groups[group] for command in commands: # Check if is a dict to get the arguments # in command if not set the arguments to empty string if isinstance(command, dict): plugin = next(six.iterkeys(command)) args = command[plugin] else: plugin = command args = '' check.update(retcode(plugin, args, group)) current_value = 0 new_value = int(check[group]['status']) if group in data: current_value = int(data[group]['status']) if (new_value > current_value) or (group not in data): if group not in data: data[group] = {} data[group]['status'] = new_value return data
[ "def", "retcode_pillar", "(", "pillar_name", ")", ":", "groups", "=", "__salt__", "[", "'pillar.get'", "]", "(", "pillar_name", ")", "check", "=", "{", "}", "data", "=", "{", "}", "for", "group", "in", "groups", ":", "commands", "=", "groups", "[", "gr...
Run one or more nagios plugins from pillar data and get the result of cmd.retcode The pillar have to be in this format:: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - check_apt ------- webserver is the role to check, the next keys are the group and the items the check with the arguments if needed You must to group different checks(one o more) and always it will return the highest value of all the checks CLI Example: .. code-block:: bash salt '*' nagios.retcode webserver
[ "Run", "one", "or", "more", "nagios", "plugins", "from", "pillar", "data", "and", "get", "the", "result", "of", "cmd", ".", "retcode", "The", "pillar", "have", "to", "be", "in", "this", "format", "::" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios.py#L131-L189
train
saltstack/salt
salt/modules/nagios.py
list_plugins
def list_plugins(): ''' List all the nagios plugins CLI Example: .. code-block:: bash salt '*' nagios.list_plugins ''' plugin_list = os.listdir(PLUGINDIR) ret = [] for plugin in plugin_list: # Check if execute bit stat_f = os.path.join(PLUGINDIR, plugin) execute_bit = stat.S_IXUSR & os.stat(stat_f)[stat.ST_MODE] if execute_bit: ret.append(plugin) return ret
python
def list_plugins(): ''' List all the nagios plugins CLI Example: .. code-block:: bash salt '*' nagios.list_plugins ''' plugin_list = os.listdir(PLUGINDIR) ret = [] for plugin in plugin_list: # Check if execute bit stat_f = os.path.join(PLUGINDIR, plugin) execute_bit = stat.S_IXUSR & os.stat(stat_f)[stat.ST_MODE] if execute_bit: ret.append(plugin) return ret
[ "def", "list_plugins", "(", ")", ":", "plugin_list", "=", "os", ".", "listdir", "(", "PLUGINDIR", ")", "ret", "=", "[", "]", "for", "plugin", "in", "plugin_list", ":", "# Check if execute bit", "stat_f", "=", "os", ".", "path", ".", "join", "(", "PLUGIND...
List all the nagios plugins CLI Example: .. code-block:: bash salt '*' nagios.list_plugins
[ "List", "all", "the", "nagios", "plugins" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios.py#L255-L273
train
saltstack/salt
salt/states/cyg.py
installed
def installed(name, cyg_arch='x86_64', mirrors=None): ''' Make sure that a package is installed. name The name of the package to install cyg_arch : x86_64 The cygwin architecture to install the package into. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.installed: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if cyg_arch not in ['x86', 'x86_64']: ret['result'] = False ret['comment'] = 'The \'cyg_arch\' argument must\ be one of \'x86\' or \'x86_64\'' return ret LOG.debug('Installed State: Initial Mirror list: %s', mirrors) if not __salt__['cyg.check_valid_package'](name, cyg_arch=cyg_arch, mirrors=mirrors): ret['result'] = False ret['comment'] = 'Invalid package name.' return ret pkgs = __salt__['cyg.list'](name, cyg_arch) if name in pkgs: ret['result'] = True ret['comment'] = 'Package is already installed.' return ret if __opts__['test']: ret['comment'] = 'The package {0} would\ have been installed'.format(name) return ret if __salt__['cyg.install'](name, cyg_arch=cyg_arch, mirrors=mirrors): ret['result'] = True ret['changes'][name] = 'Installed' ret['comment'] = 'Package was successfully installed' else: ret['result'] = False ret['comment'] = 'Could not install package.' return ret
python
def installed(name, cyg_arch='x86_64', mirrors=None): ''' Make sure that a package is installed. name The name of the package to install cyg_arch : x86_64 The cygwin architecture to install the package into. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.installed: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if cyg_arch not in ['x86', 'x86_64']: ret['result'] = False ret['comment'] = 'The \'cyg_arch\' argument must\ be one of \'x86\' or \'x86_64\'' return ret LOG.debug('Installed State: Initial Mirror list: %s', mirrors) if not __salt__['cyg.check_valid_package'](name, cyg_arch=cyg_arch, mirrors=mirrors): ret['result'] = False ret['comment'] = 'Invalid package name.' return ret pkgs = __salt__['cyg.list'](name, cyg_arch) if name in pkgs: ret['result'] = True ret['comment'] = 'Package is already installed.' return ret if __opts__['test']: ret['comment'] = 'The package {0} would\ have been installed'.format(name) return ret if __salt__['cyg.install'](name, cyg_arch=cyg_arch, mirrors=mirrors): ret['result'] = True ret['changes'][name] = 'Installed' ret['comment'] = 'Package was successfully installed' else: ret['result'] = False ret['comment'] = 'Could not install package.' return ret
[ "def", "installed", "(", "name", ",", "cyg_arch", "=", "'x86_64'", ",", "mirrors", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "if",...
Make sure that a package is installed. name The name of the package to install cyg_arch : x86_64 The cygwin architecture to install the package into. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.installed: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key
[ "Make", "sure", "that", "a", "package", "is", "installed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cyg.py#L26-L91
train
saltstack/salt
salt/states/cyg.py
removed
def removed(name, cyg_arch='x86_64', mirrors=None): ''' Make sure that a package is not installed. name The name of the package to uninstall cyg_arch : x86_64 The cygwin architecture to remove the package from. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.removed: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if cyg_arch not in ['x86', 'x86_64']: ret['result'] = False ret['comment'] = 'The \'cyg_arch\' argument must\ be one of \'x86\' or \'x86_64\'' return ret if not __salt__['cyg.check_valid_package'](name, cyg_arch=cyg_arch, mirrors=mirrors): ret['result'] = False ret['comment'] = 'Invalid package name.' return ret if name not in __salt__['cyg.list'](name, cyg_arch): ret['result'] = True ret['comment'] = 'Package is not installed.' return ret if __opts__['test']: ret['comment'] = 'The package {0} would have been removed'.format(name) return ret if __salt__['cyg.uninstall'](name, cyg_arch): ret['result'] = True ret['changes'][name] = 'Removed' ret['comment'] = 'Package was successfully removed.' else: ret['result'] = False ret['comment'] = 'Could not remove package.' return ret
python
def removed(name, cyg_arch='x86_64', mirrors=None): ''' Make sure that a package is not installed. name The name of the package to uninstall cyg_arch : x86_64 The cygwin architecture to remove the package from. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.removed: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} if cyg_arch not in ['x86', 'x86_64']: ret['result'] = False ret['comment'] = 'The \'cyg_arch\' argument must\ be one of \'x86\' or \'x86_64\'' return ret if not __salt__['cyg.check_valid_package'](name, cyg_arch=cyg_arch, mirrors=mirrors): ret['result'] = False ret['comment'] = 'Invalid package name.' return ret if name not in __salt__['cyg.list'](name, cyg_arch): ret['result'] = True ret['comment'] = 'Package is not installed.' return ret if __opts__['test']: ret['comment'] = 'The package {0} would have been removed'.format(name) return ret if __salt__['cyg.uninstall'](name, cyg_arch): ret['result'] = True ret['changes'][name] = 'Removed' ret['comment'] = 'Package was successfully removed.' else: ret['result'] = False ret['comment'] = 'Could not remove package.' return ret
[ "def", "removed", "(", "name", ",", "cyg_arch", "=", "'x86_64'", ",", "mirrors", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "if", ...
Make sure that a package is not installed. name The name of the package to uninstall cyg_arch : x86_64 The cygwin architecture to remove the package from. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.removed: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key
[ "Make", "sure", "that", "a", "package", "is", "not", "installed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cyg.py#L94-L149
train
saltstack/salt
salt/states/cyg.py
updated
def updated(name=None, cyg_arch='x86_64', mirrors=None): ''' Make sure all packages are up to date. name : None No affect, salt fails poorly without the arg available cyg_arch : x86_64 The cygwin architecture to update. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.updated: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key ''' ret = {'name': 'cyg.updated', 'result': None, 'comment': '', 'changes': {}} if cyg_arch not in ['x86', 'x86_64']: ret['result'] = False ret['comment'] = 'The \'cyg_arch\' argument must\ be one of \'x86\' or \'x86_64\'' return ret if __opts__['test']: ret['comment'] = 'All packages would have been updated' return ret if not mirrors: LOG.warning('No mirror given, using the default.') before = __salt__['cyg.list'](cyg_arch=cyg_arch) if __salt__['cyg.update'](cyg_arch, mirrors=mirrors): after = __salt__['cyg.list'](cyg_arch=cyg_arch) differ = DictDiffer(after, before) ret['result'] = True if differ.same(): ret['comment'] = 'Nothing to update.' else: ret['changes']['added'] = list(differ.added()) ret['changes']['removed'] = list(differ.removed()) ret['changes']['changed'] = list(differ.changed()) ret['comment'] = 'All packages successfully updated.' else: ret['result'] = False ret['comment'] = 'Could not update packages.' return ret
python
def updated(name=None, cyg_arch='x86_64', mirrors=None): ''' Make sure all packages are up to date. name : None No affect, salt fails poorly without the arg available cyg_arch : x86_64 The cygwin architecture to update. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.updated: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key ''' ret = {'name': 'cyg.updated', 'result': None, 'comment': '', 'changes': {}} if cyg_arch not in ['x86', 'x86_64']: ret['result'] = False ret['comment'] = 'The \'cyg_arch\' argument must\ be one of \'x86\' or \'x86_64\'' return ret if __opts__['test']: ret['comment'] = 'All packages would have been updated' return ret if not mirrors: LOG.warning('No mirror given, using the default.') before = __salt__['cyg.list'](cyg_arch=cyg_arch) if __salt__['cyg.update'](cyg_arch, mirrors=mirrors): after = __salt__['cyg.list'](cyg_arch=cyg_arch) differ = DictDiffer(after, before) ret['result'] = True if differ.same(): ret['comment'] = 'Nothing to update.' else: ret['changes']['added'] = list(differ.added()) ret['changes']['removed'] = list(differ.removed()) ret['changes']['changed'] = list(differ.changed()) ret['comment'] = 'All packages successfully updated.' else: ret['result'] = False ret['comment'] = 'Could not update packages.' return ret
[ "def", "updated", "(", "name", "=", "None", ",", "cyg_arch", "=", "'x86_64'", ",", "mirrors", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "'cyg.updated'", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{...
Make sure all packages are up to date. name : None No affect, salt fails poorly without the arg available cyg_arch : x86_64 The cygwin architecture to update. Current options are x86 and x86_64 mirrors : None List of mirrors to check. None will use a default mirror (kernel.org) CLI Example: .. code-block:: yaml rsync: cyg.updated: - mirrors: - http://mirror/without/public/key: "" - http://mirror/with/public/key: http://url/of/public/key
[ "Make", "sure", "all", "packages", "are", "up", "to", "date", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cyg.py#L152-L207
train
saltstack/salt
salt/pillar/varstack_pillar.py
ext_pillar
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 conf): ''' Parse varstack data and return the result ''' vs = varstack.Varstack(config_filename=conf) return vs.evaluate(__grains__)
python
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 conf): ''' Parse varstack data and return the result ''' vs = varstack.Varstack(config_filename=conf) return vs.evaluate(__grains__)
[ "def", "ext_pillar", "(", "minion_id", ",", "# pylint: disable=W0613", "pillar", ",", "# pylint: disable=W0613", "conf", ")", ":", "vs", "=", "varstack", ".", "Varstack", "(", "config_filename", "=", "conf", ")", "return", "vs", ".", "evaluate", "(", "__grains__...
Parse varstack data and return the result
[ "Parse", "varstack", "data", "and", "return", "the", "result" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/varstack_pillar.py#L40-L47
train
saltstack/salt
salt/utils/pagerduty.py
query
def query(method='GET', profile_dict=None, url=None, path='api/v1', action=None, api_key=None, service=None, params=None, data=None, subdomain=None, client_url=None, description=None, opts=None, verify_ssl=True): ''' Query the PagerDuty API ''' user_agent = 'SaltStack {0}'.format(__version__) if opts is None: opts = {} if isinstance(profile_dict, dict): creds = profile_dict else: creds = {} if api_key is not None: creds['pagerduty.api_key'] = api_key if service is not None: creds['pagerduty.service'] = service if subdomain is not None: creds['pagerduty.subdomain'] = subdomain if client_url is None: client_url = 'https://{0}.pagerduty.com'.format( creds['pagerduty.subdomain'] ) if url is None: url = 'https://{0}.pagerduty.com/{1}/{2}'.format( creds['pagerduty.subdomain'], path, action ) if params is None: params = {} if data is None: data = {} data['client'] = user_agent # pagerduty.service is not documented. While it makes sense to have in # some cases, don't force it when it is not defined. if 'pagerduty.service' in creds and creds['pagerduty.service'] is not None: data['service_key'] = creds['pagerduty.service'] data['client_url'] = client_url if 'event_type' not in data: data['event_type'] = 'trigger' if 'description' not in data: if not description: data['description'] = 'SaltStack Event Triggered' else: data['description'] = description headers = { 'User-Agent': user_agent, 'Authorization': 'Token token={0}'.format(creds['pagerduty.api_key']) } if method == 'GET': data = {} else: headers['Content-type'] = 'application/json' result = salt.utils.http.query( url, method, params=params, header_dict=headers, data=salt.utils.json.dumps(data), decode=False, text=True, opts=opts, ) return result['text']
python
def query(method='GET', profile_dict=None, url=None, path='api/v1', action=None, api_key=None, service=None, params=None, data=None, subdomain=None, client_url=None, description=None, opts=None, verify_ssl=True): ''' Query the PagerDuty API ''' user_agent = 'SaltStack {0}'.format(__version__) if opts is None: opts = {} if isinstance(profile_dict, dict): creds = profile_dict else: creds = {} if api_key is not None: creds['pagerduty.api_key'] = api_key if service is not None: creds['pagerduty.service'] = service if subdomain is not None: creds['pagerduty.subdomain'] = subdomain if client_url is None: client_url = 'https://{0}.pagerduty.com'.format( creds['pagerduty.subdomain'] ) if url is None: url = 'https://{0}.pagerduty.com/{1}/{2}'.format( creds['pagerduty.subdomain'], path, action ) if params is None: params = {} if data is None: data = {} data['client'] = user_agent # pagerduty.service is not documented. While it makes sense to have in # some cases, don't force it when it is not defined. if 'pagerduty.service' in creds and creds['pagerduty.service'] is not None: data['service_key'] = creds['pagerduty.service'] data['client_url'] = client_url if 'event_type' not in data: data['event_type'] = 'trigger' if 'description' not in data: if not description: data['description'] = 'SaltStack Event Triggered' else: data['description'] = description headers = { 'User-Agent': user_agent, 'Authorization': 'Token token={0}'.format(creds['pagerduty.api_key']) } if method == 'GET': data = {} else: headers['Content-type'] = 'application/json' result = salt.utils.http.query( url, method, params=params, header_dict=headers, data=salt.utils.json.dumps(data), decode=False, text=True, opts=opts, ) return result['text']
[ "def", "query", "(", "method", "=", "'GET'", ",", "profile_dict", "=", "None", ",", "url", "=", "None", ",", "path", "=", "'api/v1'", ",", "action", "=", "None", ",", "api_key", "=", "None", ",", "service", "=", "None", ",", "params", "=", "None", ...
Query the PagerDuty API
[ "Query", "the", "PagerDuty", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pagerduty.py#L29-L108
train
saltstack/salt
salt/utils/pagerduty.py
list_items
def list_items(action, key, profile_dict=None, api_key=None, opts=None): ''' List items belonging to an API call. Used for list_services() and list_incidents() ''' items = salt.utils.json.loads(query( profile_dict=profile_dict, api_key=api_key, action=action, opts=opts )) ret = {} for item in items[action]: ret[item[key]] = item return ret
python
def list_items(action, key, profile_dict=None, api_key=None, opts=None): ''' List items belonging to an API call. Used for list_services() and list_incidents() ''' items = salt.utils.json.loads(query( profile_dict=profile_dict, api_key=api_key, action=action, opts=opts )) ret = {} for item in items[action]: ret[item[key]] = item return ret
[ "def", "list_items", "(", "action", ",", "key", ",", "profile_dict", "=", "None", ",", "api_key", "=", "None", ",", "opts", "=", "None", ")", ":", "items", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "query", "(", "profile_dict", "=", ...
List items belonging to an API call. Used for list_services() and list_incidents()
[ "List", "items", "belonging", "to", "an", "API", "call", ".", "Used", "for", "list_services", "()", "and", "list_incidents", "()" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pagerduty.py#L111-L125
train
saltstack/salt
salt/modules/aix_group.py
add
def add(name, gid=None, system=False, root=None): ''' Add the specified group CLI Example: .. code-block:: bash salt '*' group.add foo 3456 ''' cmd = 'mkgroup ' if system and root is not None: cmd += '-a ' if gid: cmd += 'id={0} '.format(gid) cmd += name ret = __salt__['cmd.run_all'](cmd, python_shell=False) return not ret['retcode']
python
def add(name, gid=None, system=False, root=None): ''' Add the specified group CLI Example: .. code-block:: bash salt '*' group.add foo 3456 ''' cmd = 'mkgroup ' if system and root is not None: cmd += '-a ' if gid: cmd += 'id={0} '.format(gid) cmd += name ret = __salt__['cmd.run_all'](cmd, python_shell=False) return not ret['retcode']
[ "def", "add", "(", "name", ",", "gid", "=", "None", ",", "system", "=", "False", ",", "root", "=", "None", ")", ":", "cmd", "=", "'mkgroup '", "if", "system", "and", "root", "is", "not", "None", ":", "cmd", "+=", "'-a '", "if", "gid", ":", "cmd",...
Add the specified group CLI Example: .. code-block:: bash salt '*' group.add foo 3456
[ "Add", "the", "specified", "group" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aix_group.py#L39-L60
train
saltstack/salt
salt/modules/aix_group.py
info
def info(name): ''' Return information about a group CLI Example: .. code-block:: bash salt '*' group.info foo ''' try: grinfo = grp.getgrnam(name) except KeyError: return {} else: return {'name': grinfo.gr_name, 'passwd': grinfo.gr_passwd, 'gid': grinfo.gr_gid, 'members': grinfo.gr_mem}
python
def info(name): ''' Return information about a group CLI Example: .. code-block:: bash salt '*' group.info foo ''' try: grinfo = grp.getgrnam(name) except KeyError: return {} else: return {'name': grinfo.gr_name, 'passwd': grinfo.gr_passwd, 'gid': grinfo.gr_gid, 'members': grinfo.gr_mem}
[ "def", "info", "(", "name", ")", ":", "try", ":", "grinfo", "=", "grp", ".", "getgrnam", "(", "name", ")", "except", "KeyError", ":", "return", "{", "}", "else", ":", "return", "{", "'name'", ":", "grinfo", ".", "gr_name", ",", "'passwd'", ":", "gr...
Return information about a group CLI Example: .. code-block:: bash salt '*' group.info foo
[ "Return", "information", "about", "a", "group" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aix_group.py#L78-L96
train
saltstack/salt
salt/modules/aix_group.py
getent
def getent(refresh=False): ''' Return info on all groups CLI Example: .. code-block:: bash salt '*' group.getent ''' if 'group.getent' in __context__ and not refresh: return __context__['group.getent'] ret = [] for grinfo in grp.getgrall(): ret.append(info(grinfo.gr_name)) __context__['group.getent'] = ret return ret
python
def getent(refresh=False): ''' Return info on all groups CLI Example: .. code-block:: bash salt '*' group.getent ''' if 'group.getent' in __context__ and not refresh: return __context__['group.getent'] ret = [] for grinfo in grp.getgrall(): ret.append(info(grinfo.gr_name)) __context__['group.getent'] = ret return ret
[ "def", "getent", "(", "refresh", "=", "False", ")", ":", "if", "'group.getent'", "in", "__context__", "and", "not", "refresh", ":", "return", "__context__", "[", "'group.getent'", "]", "ret", "=", "[", "]", "for", "grinfo", "in", "grp", ".", "getgrall", ...
Return info on all groups CLI Example: .. code-block:: bash salt '*' group.getent
[ "Return", "info", "on", "all", "groups" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aix_group.py#L99-L117
train
saltstack/salt
salt/modules/aix_group.py
deluser
def deluser(name, username, root=None): ''' Remove a user from the group. CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If group is not present then returns True. ''' grp_info = __salt__['group.info'](name) try: if username in grp_info['members']: cmd = 'chgrpmem -m - {0} {1}'.format(username, name) ret = __salt__['cmd.run'](cmd, python_shell=False) return not ret['retcode'] else: return True except Exception: return True
python
def deluser(name, username, root=None): ''' Remove a user from the group. CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If group is not present then returns True. ''' grp_info = __salt__['group.info'](name) try: if username in grp_info['members']: cmd = 'chgrpmem -m - {0} {1}'.format(username, name) ret = __salt__['cmd.run'](cmd, python_shell=False) return not ret['retcode'] else: return True except Exception: return True
[ "def", "deluser", "(", "name", ",", "username", ",", "root", "=", "None", ")", ":", "grp_info", "=", "__salt__", "[", "'group.info'", "]", "(", "name", ")", "try", ":", "if", "username", "in", "grp_info", "[", "'members'", "]", ":", "cmd", "=", "'chg...
Remove a user from the group. CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If group is not present then returns True.
[ "Remove", "a", "user", "from", "the", "group", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aix_group.py#L161-L183
train
saltstack/salt
salt/modules/aix_group.py
members
def members(name, members_list, root=None): ''' Replaces members of the group with a provided list. CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,... ''' cmd = 'chgrpmem -m = {0} {1}'.format(members_list, name) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) return not retcode
python
def members(name, members_list, root=None): ''' Replaces members of the group with a provided list. CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,... ''' cmd = 'chgrpmem -m = {0} {1}'.format(members_list, name) retcode = __salt__['cmd.retcode'](cmd, python_shell=False) return not retcode
[ "def", "members", "(", "name", ",", "members_list", ",", "root", "=", "None", ")", ":", "cmd", "=", "'chgrpmem -m = {0} {1}'", ".", "format", "(", "members_list", ",", "name", ")", "retcode", "=", "__salt__", "[", "'cmd.retcode'", "]", "(", "cmd", ",", "...
Replaces members of the group with a provided list. CLI Example: salt '*' group.members foo 'user1,user2,user3,...' Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,...
[ "Replaces", "members", "of", "the", "group", "with", "a", "provided", "list", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aix_group.py#L186-L200
train
saltstack/salt
salt/modules/pyenv.py
install
def install(runas=None, path=None): ''' Install pyenv systemwide CLI Example: .. code-block:: bash salt '*' pyenv.install ''' path = path or _pyenv_path(runas) path = os.path.expanduser(path) return _install_pyenv(path, runas)
python
def install(runas=None, path=None): ''' Install pyenv systemwide CLI Example: .. code-block:: bash salt '*' pyenv.install ''' path = path or _pyenv_path(runas) path = os.path.expanduser(path) return _install_pyenv(path, runas)
[ "def", "install", "(", "runas", "=", "None", ",", "path", "=", "None", ")", ":", "path", "=", "path", "or", "_pyenv_path", "(", "runas", ")", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "return", "_install_pyenv", "(", "path"...
Install pyenv systemwide CLI Example: .. code-block:: bash salt '*' pyenv.install
[ "Install", "pyenv", "systemwide" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pyenv.py#L105-L117
train
saltstack/salt
salt/modules/pyenv.py
update
def update(runas=None, path=None): ''' Updates the current versions of pyenv and python-Build CLI Example: .. code-block:: bash salt '*' pyenv.update ''' path = path or _pyenv_path(runas) path = os.path.expanduser(path) return _update_pyenv(path, runas)
python
def update(runas=None, path=None): ''' Updates the current versions of pyenv and python-Build CLI Example: .. code-block:: bash salt '*' pyenv.update ''' path = path or _pyenv_path(runas) path = os.path.expanduser(path) return _update_pyenv(path, runas)
[ "def", "update", "(", "runas", "=", "None", ",", "path", "=", "None", ")", ":", "path", "=", "path", "or", "_pyenv_path", "(", "runas", ")", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "return", "_update_pyenv", "(", "path", ...
Updates the current versions of pyenv and python-Build CLI Example: .. code-block:: bash salt '*' pyenv.update
[ "Updates", "the", "current", "versions", "of", "pyenv", "and", "python", "-", "Build" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pyenv.py#L120-L133
train
saltstack/salt
salt/modules/pyenv.py
install_python
def install_python(python, runas=None): ''' Install a python implementation. python The version of python to install, should match one of the versions listed by pyenv.list CLI Example: .. code-block:: bash salt '*' pyenv.install_python 2.0.0-p0 ''' python = re.sub(r'^python-', '', python) env = None env_list = [] if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'): env_list.append('MAKE=gmake') if __salt__['config.option']('pyenv.build_env'): env_list.append(__salt__['config.option']('pyenv.build_env')) if env_list: env = ' '.join(env_list) ret = {} ret = _pyenv_exec('install', python, env=env, runas=runas, ret=ret) if ret['retcode'] == 0: rehash(runas=runas) return ret['stderr'] else: # Cleanup the failed installation so it doesn't list as installed uninstall_python(python, runas=runas) return False
python
def install_python(python, runas=None): ''' Install a python implementation. python The version of python to install, should match one of the versions listed by pyenv.list CLI Example: .. code-block:: bash salt '*' pyenv.install_python 2.0.0-p0 ''' python = re.sub(r'^python-', '', python) env = None env_list = [] if __grains__['os'] in ('FreeBSD', 'NetBSD', 'OpenBSD'): env_list.append('MAKE=gmake') if __salt__['config.option']('pyenv.build_env'): env_list.append(__salt__['config.option']('pyenv.build_env')) if env_list: env = ' '.join(env_list) ret = {} ret = _pyenv_exec('install', python, env=env, runas=runas, ret=ret) if ret['retcode'] == 0: rehash(runas=runas) return ret['stderr'] else: # Cleanup the failed installation so it doesn't list as installed uninstall_python(python, runas=runas) return False
[ "def", "install_python", "(", "python", ",", "runas", "=", "None", ")", ":", "python", "=", "re", ".", "sub", "(", "r'^python-'", ",", "''", ",", "python", ")", "env", "=", "None", "env_list", "=", "[", "]", "if", "__grains__", "[", "'os'", "]", "i...
Install a python implementation. python The version of python to install, should match one of the versions listed by pyenv.list CLI Example: .. code-block:: bash salt '*' pyenv.install_python 2.0.0-p0
[ "Install", "a", "python", "implementation", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pyenv.py#L149-L185
train
saltstack/salt
salt/modules/pyenv.py
uninstall_python
def uninstall_python(python, runas=None): ''' Uninstall a python implementation. python The version of python to uninstall. Should match one of the versions listed by :mod:`pyenv.versions <salt.modules.pyenv.versions>` CLI Example: .. code-block:: bash salt '*' pyenv.uninstall_python 2.0.0-p0 ''' python = re.sub(r'^python-', '', python) args = '--force {0}'.format(python) _pyenv_exec('uninstall', args, runas=runas) return True
python
def uninstall_python(python, runas=None): ''' Uninstall a python implementation. python The version of python to uninstall. Should match one of the versions listed by :mod:`pyenv.versions <salt.modules.pyenv.versions>` CLI Example: .. code-block:: bash salt '*' pyenv.uninstall_python 2.0.0-p0 ''' python = re.sub(r'^python-', '', python) args = '--force {0}'.format(python) _pyenv_exec('uninstall', args, runas=runas) return True
[ "def", "uninstall_python", "(", "python", ",", "runas", "=", "None", ")", ":", "python", "=", "re", ".", "sub", "(", "r'^python-'", ",", "''", ",", "python", ")", "args", "=", "'--force {0}'", ".", "format", "(", "python", ")", "_pyenv_exec", "(", "'un...
Uninstall a python implementation. python The version of python to uninstall. Should match one of the versions listed by :mod:`pyenv.versions <salt.modules.pyenv.versions>` CLI Example: .. code-block:: bash salt '*' pyenv.uninstall_python 2.0.0-p0
[ "Uninstall", "a", "python", "implementation", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pyenv.py#L188-L206
train