INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Wrapper for commands to be run against Windows boxes using WinRM. | def winrm_cmd(session, command, flags, **kwargs):
'''
Wrapper for commands to be run against Windows boxes using WinRM.
'''
log.debug('Executing WinRM command: %s %s', command, flags)
# rebuild the session to ensure we haven't timed out
session.protocol.transport.build_session()
r = session.... |
Wrapper for commands to be run as root | def root_cmd(command, tty, sudo, allow_failure=False, **kwargs):
'''
Wrapper for commands to be run as root
'''
logging_command = command
sudo_password = kwargs.get('sudo_password', None)
if sudo:
if sudo_password is None:
command = 'sudo {0}'.format(command)
log... |
This function is called from a multiprocess instance to wait for a minion to become available to receive salt commands | def check_auth(name, sock_dir=None, queue=None, timeout=300):
'''
This function is called from a multiprocess instance, to wait for a minion
to become available to receive salt commands
'''
event = salt.utils.event.SaltEvent('master', sock_dir, listen=True)
starttime = time.mktime(time.localtime... |
Converts an IP address to an integer | def ip_to_int(ip):
'''
Converts an IP address to an integer
'''
ret = 0
for octet in ip.split('.'):
ret = ret * 256 + int(octet)
return ret |
Determines whether an IP address falls within one of the private IP ranges | def is_public_ip(ip):
'''
Determines whether an IP address falls within one of the private IP ranges
'''
if ':' in ip:
# ipv6
if ip.startswith('fe80:'):
# ipv6 link local
return False
return True
addr = ip_to_int(ip)
if 167772160 < addr < 184549375... |
Check whether the specified name contains invalid characters | def check_name(name, safe_chars):
'''
Check whether the specified name contains invalid characters
'''
regexp = re.compile('[^{0}]'.format(safe_chars))
if regexp.search(name):
raise SaltCloudException(
'{0} contains characters not supported by this cloud provider. '
'... |
Remove a host from the known_hosts file | def remove_sshkey(host, known_hosts=None):
'''
Remove a host from the known_hosts file
'''
if known_hosts is None:
if 'HOME' in os.environ:
known_hosts = '{0}/.ssh/known_hosts'.format(os.environ['HOME'])
else:
try:
known_hosts = '{0}/.ssh/known_hos... |
Return a list of the VMs that are on the provider with select fields | def list_nodes_select(nodes, selection, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called '
'with -f or --function.'
)
if 'e... |
Lock a file ; if it is already locked then wait for it to become available before locking it. | def lock_file(filename, interval=.5, timeout=15):
'''
Lock a file; if it is already locked, then wait for it to become available
before locking it.
Note that these locks are only recognized by Salt Cloud, and not other
programs or platforms.
'''
log.trace('Attempting to obtain lock for %s',... |
Unlock a locked file | def unlock_file(filename):
'''
Unlock a locked file
Note that these locks are only recognized by Salt Cloud, and not other
programs or platforms.
'''
log.trace('Removing lock for %s', filename)
lock = filename + '.lock'
try:
os.remove(lock)
except OSError as exc:
log... |
Add an entry to the cachedir index. This generally only needs to happen when a new instance is created. This entry should contain: | def cachedir_index_add(minion_id, profile, driver, provider, base=None):
'''
Add an entry to the cachedir index. This generally only needs to happen when
a new instance is created. This entry should contain:
.. code-block:: yaml
- minion_id
- profile used to create the instance
... |
Delete an entry from the cachedir index. This generally only needs to happen when an instance is deleted. | def cachedir_index_del(minion_id, base=None):
'''
Delete an entry from the cachedir index. This generally only needs to happen
when an instance is deleted.
'''
base = init_cachedir(base)
index_file = os.path.join(base, 'index.p')
lock_file(index_file)
if os.path.exists(index_file):
... |
Initialize the cachedir needed for Salt Cloud to keep track of minions | def init_cachedir(base=None):
'''
Initialize the cachedir needed for Salt Cloud to keep track of minions
'''
if base is None:
base = __opts__['cachedir']
needed_dirs = (base,
os.path.join(base, 'requested'),
os.path.join(base, 'active'))
for dir_ in ... |
Creates an entry in the requested/ cachedir. This means that Salt Cloud has made a request to a cloud provider to create an instance but it has not yet verified that the instance properly exists. | def request_minion_cachedir(
minion_id,
opts=None,
fingerprint='',
pubkey=None,
provider=None,
base=None,
):
'''
Creates an entry in the requested/ cachedir. This means that Salt Cloud has
made a request to a cloud provider to create an instance, but it has no... |
Changes the info inside a minion s cachedir entry. The type of cachedir must be specified ( i. e. requested or active ). A dict is also passed in which contains the data to be changed. | def change_minion_cachedir(
minion_id,
cachedir,
data=None,
base=None,
):
'''
Changes the info inside a minion's cachedir entry. The type of cachedir
must be specified (i.e., 'requested' or 'active'). A dict is also passed in
which contains the data to be changed.
Ex... |
Moves a minion from the requested/ cachedir into the active/ cachedir. This means that Salt Cloud has verified that a requested instance properly exists and should be expected to exist from here on out. | def activate_minion_cachedir(minion_id, base=None):
'''
Moves a minion from the requested/ cachedir into the active/ cachedir. This
means that Salt Cloud has verified that a requested instance properly
exists, and should be expected to exist from here on out.
'''
if base is None:
base = ... |
Deletes a minion s entry from the cloud cachedir. It will search through all cachedirs to find the minion s cache file. Needs update_cachedir set to True. | def delete_minion_cachedir(minion_id, provider, opts, base=None):
'''
Deletes a minion's entry from the cloud cachedir. It will search through
all cachedirs to find the minion's cache file.
Needs `update_cachedir` set to True.
'''
if isinstance(opts, dict):
__opts__.update(opts)
if ... |
Return a list of minion data from the cloud cache rather from the cloud providers themselves. This is the cloud cache version of list_nodes_full (). | def list_cache_nodes_full(opts=None, provider=None, base=None):
'''
Return a list of minion data from the cloud cache, rather from the cloud
providers themselves. This is the cloud cache version of list_nodes_full().
'''
if opts is None:
opts = __opts__
if opts.get('update_cachedir', Fal... |
Update the salt - bootstrap script | def update_bootstrap(config, url=None):
'''
Update the salt-bootstrap script
url can be one of:
- The URL to fetch the bootstrap script from
- The absolute path to the bootstrap
- The content of the bootstrap script
'''
default_url = config.get('bootstrap_script_url',
... |
If configured to do so update the cloud cachedir with the current list of nodes. Also fires configured events pertaining to the node list. | def cache_node_list(nodes, provider, opts):
'''
If configured to do so, update the cloud cachedir with the current list of
nodes. Also fires configured events pertaining to the node list.
.. versionadded:: 2014.7.0
'''
if 'update_cachedir' not in opts or not opts['update_cachedir']:
ret... |
Cache node individually | def cache_node(node, provider, opts):
'''
Cache node individually
.. versionadded:: 2014.7.0
'''
if isinstance(opts, dict):
__opts__.update(opts)
if 'update_cachedir' not in __opts__ or not __opts__['update_cachedir']:
return
if not os.path.exists(os.path.join(__opts__['ca... |
Check list of nodes to see if any nodes which were previously known about in the cache have been removed from the node list. | def missing_node_cache(prov_dir, node_list, provider, opts):
'''
Check list of nodes to see if any nodes which were previously known about
in the cache have been removed from the node list.
This function will only run if configured to do so in the main Salt Cloud
configuration file (normally /etc/s... |
Check new node data against current cache. If data differ fire an event which consists of the new node data. | def diff_node_cache(prov_dir, node, new_data, opts):
'''
Check new node data against current cache. If data differ, fire an event
which consists of the new node data.
This function will only run if configured to do so in the main Salt Cloud
configuration file (normally /etc/salt/cloud).
.. cod... |
Strip out user - configured sensitive event data. The fields to be stripped are configured in the main Salt Cloud configuration file usually/ etc/ salt/ cloud. | def _strip_cache_events(data, opts):
'''
Strip out user-configured sensitive event data. The fields to be stripped
are configured in the main Salt Cloud configuration file, usually
``/etc/salt/cloud``.
.. code-block: yaml
cache_event_strip_fields:
- password
- priv_key
... |
Helper method to try its best to convert any Unicode text into ASCII without stack tracing since salt internally does not handle Unicode strings | def _salt_cloud_force_ascii(exc):
'''
Helper method to try its best to convert any Unicode text into ASCII
without stack tracing since salt internally does not handle Unicode strings
This method is not supposed to be used directly. Once
`py:module: salt.utils.cloud` is imported this method register... |
Retrieve particular user s password for a specified credential set from system keyring. | def retrieve_password_from_keyring(credential_id, username):
'''
Retrieve particular user's password for a specified credential set from system keyring.
'''
try:
import keyring # pylint: disable=import-error
return keyring.get_password(credential_id, username)
except ImportError:
... |
Saves provider password in system keyring | def _save_password_in_keyring(credential_id, username, password):
'''
Saves provider password in system keyring
'''
try:
import keyring # pylint: disable=import-error
return keyring.set_password(credential_id, username, password)
except ImportError:
log.error('Tried to store... |
Interactively prompts user for a password and stores it in system keyring | def store_password_in_keyring(credential_id, username, password=None):
'''
Interactively prompts user for a password and stores it in system keyring
'''
try:
# pylint: disable=import-error
import keyring
import keyring.errors
# pylint: enable=import-error
if passw... |
Accepts index in form of a string Returns final value Example: dictionary = { a: { b: { c: foobar }}} index_string = a b c returns foobar | def _unwrap_dict(dictionary, index_string):
'''
Accepts index in form of a string
Returns final value
Example: dictionary = {'a': {'b': {'c': 'foobar'}}}
index_string = 'a,b,c'
returns 'foobar'
'''
index = index_string.split(',')
for k in index:
dictionary =... |
Waits until the function retrieves some required argument. NOTE: Tested with ec2 describe_volumes and describe_snapshots only. | def run_func_until_ret_arg(fun, kwargs, fun_call=None,
argument_being_watched=None, required_argument_response=None):
'''
Waits until the function retrieves some required argument.
NOTE: Tested with ec2 describe_volumes and describe_snapshots only.
'''
status = None
wh... |
Return the salt_interface type to connect to. Either public_ips ( default ) or private_ips. | def get_salt_interface(vm_, opts):
'''
Return the salt_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
salt_host = salt.config.get_cloud_config_value(
'salt_interface', vm_, opts, default=False,
search_global=False
)
if salt_host is False:
... |
Checks that the key_path exists and the key_mode is either 0400 or 0600. | def check_key_path_and_mode(provider, key_path):
'''
Checks that the key_path exists and the key_mode is either 0400 or 0600.
Returns True or False.
.. versionadded:: 2016.3.0
provider
The provider name that the key_path to check belongs to.
key_path
The key_path to ensure th... |
Use the configured templating engine to template the userdata file | def userdata_template(opts, vm_, userdata):
'''
Use the configured templating engine to template the userdata file
'''
# No userdata, no need to template anything
if userdata is None:
return userdata
userdata_template = salt.config.get_cloud_config_value(
'userdata_template', vm... |
Removes the PAExec service and executable that was created as part of the create_service function. This does not remove any older executables or services from previous runs use cleanup () instead for that purpose. | def remove_service(self, wait_timeout=10, sleep_wait=1):
'''
Removes the PAExec service and executable that was created as part of
the create_service function. This does not remove any older executables
or services from previous runs, use cleanup() instead for that purpose.
'''
... |
Set an AES dropfile to request the master update the publish session key | def dropfile(cachedir, user=None):
'''
Set an AES dropfile to request the master update the publish session key
'''
dfn = os.path.join(cachedir, '.dfn')
# set a mask (to avoid a race condition on file creation) and store original.
with salt.utils.files.set_umask(0o277):
log.info('Rotatin... |
Generate a RSA public keypair for use with salt | def gen_keys(keydir, keyname, keysize, user=None, passphrase=None):
'''
Generate a RSA public keypair for use with salt
:param str keydir: The directory to write the keypair to
:param str keyname: The type of salt server for whom this key should be written. (i.e. 'master' or 'minion')
:param int ke... |
Load a private key from disk. timestamp above is intended to be the timestamp of the file s last modification. This fn is memoized so if it is called with the same path and timestamp ( the file s last modified time ) the second time the result is returned from the memoiziation. If the file gets modified then the params... | def _get_key_with_evict(path, timestamp, passphrase):
'''
Load a private key from disk. `timestamp` above is intended to be the
timestamp of the file's last modification. This fn is memoized so if it is
called with the same path and timestamp (the file's last modified time) the
second time the resu... |
Read a private key off the disk. Poor man s simple cache in effect here we memoize the result of calling _get_rsa_with_evict. This means the first time _get_key_with_evict is called with a path and a timestamp the result is cached. If the file ( the private key ) does not change then its timestamp will not change and t... | def get_rsa_key(path, passphrase):
'''
Read a private key off the disk. Poor man's simple cache in effect here,
we memoize the result of calling _get_rsa_with_evict. This means the first
time _get_key_with_evict is called with a path and a timestamp the result
is cached. If the file (the private ... |
Read a public key off the disk. | def get_rsa_pub_key(path):
'''
Read a public key off the disk.
'''
log.debug('salt.crypt.get_rsa_pub_key: Loading public key')
if HAS_M2:
with salt.utils.files.fopen(path, 'rb') as f:
data = f.read().replace(b'RSA ', b'')
bio = BIO.MemoryBuffer(data)
key = RSA.loa... |
Use Crypto. Signature. PKCS1_v1_5 to sign a message. Returns the signature. | def sign_message(privkey_path, message, passphrase=None):
'''
Use Crypto.Signature.PKCS1_v1_5 to sign a message. Returns the signature.
'''
key = get_rsa_key(privkey_path, passphrase)
log.debug('salt.crypt.sign_message: Signing message.')
if HAS_M2:
md = EVP.MessageDigest('sha1')
... |
Use Crypto. Signature. PKCS1_v1_5 to verify the signature on a message. Returns True for valid signature. | def verify_signature(pubkey_path, message, signature):
'''
Use Crypto.Signature.PKCS1_v1_5 to verify the signature on a message.
Returns True for valid signature.
'''
log.debug('salt.crypt.verify_signature: Loading public key')
pubkey = get_rsa_pub_key(pubkey_path)
log.debug('salt.crypt.veri... |
creates a signature for the given public - key with the given private key and writes it to sign_path | def gen_signature(priv_path, pub_path, sign_path, passphrase=None):
'''
creates a signature for the given public-key with
the given private key and writes it to sign_path
'''
with salt.utils.files.fopen(pub_path) as fp_:
mpub_64 = fp_.read()
mpub_sig = sign_message(priv_path, mpub_64, ... |
Generate an M2Crypto - compatible signature | def private_encrypt(key, message):
'''
Generate an M2Crypto-compatible signature
:param Crypto.PublicKey.RSA._RSAobj key: The RSA key object
:param str message: The message to sign
:rtype: str
:return: The signature, or an empty string if the signature operation failed
'''
if HAS_M2:
... |
Verify an M2Crypto - compatible signature | def public_decrypt(pub, message):
'''
Verify an M2Crypto-compatible signature
:param Crypto.PublicKey.RSA._RSAobj key: The RSA public key object
:param str message: The signed message to verify
:rtype: str
:return: The message (or digest) recovered from the signature, or an
empty string... |
Returns a key object for a key in the pki - dir | def __get_keys(self, name='master', passphrase=None):
'''
Returns a key object for a key in the pki-dir
'''
path = os.path.join(self.opts['pki_dir'],
name + '.pem')
if not os.path.exists(path):
log.info('Generating %s keys: %s', name, self.... |
Return the string representation of a public key in the pki - directory | def get_pub_str(self, name='master'):
'''
Return the string representation of a public key
in the pki-directory
'''
path = os.path.join(self.opts['pki_dir'],
name + '.pub')
if not os.path.isfile(path):
key = self.__get_keys()
... |
Ask for this client to reconnect to the origin | def authenticate(self, callback=None):
'''
Ask for this client to reconnect to the origin
This function will de-dupe all calls here and return a *single* future
for the sign-in-- whis way callers can all assume there aren't others
'''
# if an auth is in flight-- and not ... |
Authenticate with the master this method breaks the functional paradigm it will update the master information from a fresh sign in signing in can occur as often as needed to keep up with the revolving master AES key. | def _authenticate(self):
'''
Authenticate with the master, this method breaks the functional
paradigm, it will update the master information from a fresh sign
in, signing in can occur as often as needed to keep up with the
revolving master AES key.
:rtype: Crypticle
... |
Send a sign in request to the master sets the key information and returns a dict containing the master publish interface to bind to and the decrypted aes key for transport decryption. | def sign_in(self, timeout=60, safe=True, tries=1, channel=None):
'''
Send a sign in request to the master, sets the key information and
returns a dict containing the master publish interface to bind to
and the decrypted aes key for transport decryption.
:param int timeout: Numbe... |
Return keypair object for the minion. | def get_keys(self):
'''
Return keypair object for the minion.
:rtype: Crypto.PublicKey.RSA._RSAobj
:return: The RSA keypair
'''
# Make sure all key parent directories are accessible
user = self.opts.get('user', 'root')
salt.utils.verify.check_path_travers... |
Generates the payload used to authenticate with the master server. This payload consists of the passed in id_ and the ssh public key to encrypt the AES key sent back from the master. | def minion_sign_in_payload(self):
'''
Generates the payload used to authenticate with the master
server. This payload consists of the passed in id_ and the ssh
public key to encrypt the AES key sent back from the master.
:return: Payload dictionary
:rtype: dict
'... |
This function is used to decrypt the AES seed phrase returned from the master server. The seed phrase is decrypted with the SSH RSA host key. | def decrypt_aes(self, payload, master_pub=True):
'''
This function is used to decrypt the AES seed phrase returned from
the master server. The seed phrase is decrypted with the SSH RSA
host key.
Pass in the encrypted AES key.
Returns the decrypted AES seed key, a string
... |
Wraps the verify_signature method so we have additional checks. | def verify_pubkey_sig(self, message, sig):
'''
Wraps the verify_signature method so we have
additional checks.
:rtype: bool
:return: Success or failure of public key verification
'''
if self.opts['master_sign_key_name']:
path = os.path.join(self.opts[... |
Checks if both master and minion either sign ( master ) and verify ( minion ). If one side does not it should fail. | def check_auth_deps(self, payload):
'''
Checks if both master and minion either sign (master) and
verify (minion). If one side does not, it should fail.
:param dict payload: The incoming payload. This is a dictionary which may have the following keys:
'aes': The shared AES k... |
Return the AES key received from the master after the minion has been successfully authenticated. | def extract_aes(self, payload, master_pub=True):
'''
Return the AES key received from the master after the minion has been
successfully authenticated.
:param dict payload: The incoming payload. This is a dictionary which may have the following keys:
'aes': The shared AES key... |
Verify that the master is the same one that was previously accepted. | def verify_master(self, payload, master_pub=True):
'''
Verify that the master is the same one that was previously accepted.
:param dict payload: The incoming payload. This is a dictionary which may have the following keys:
'aes': The shared AES key
'enc': The format of t... |
Authenticate with the master this method breaks the functional paradigm it will update the master information from a fresh sign in signing in can occur as often as needed to keep up with the revolving master AES key. | def authenticate(self, _=None): # TODO: remove unused var
'''
Authenticate with the master, this method breaks the functional
paradigm, it will update the master information from a fresh sign
in, signing in can occur as often as needed to keep up with the
revolving master AES ke... |
encrypt data with AES - CBC and sign it with HMAC - SHA256 | def encrypt(self, data):
'''
encrypt data with AES-CBC and sign it with HMAC-SHA256
'''
aes_key, hmac_key = self.keys
pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
if six.PY2:
data = data + pad * chr(pad)
else:
data = data + s... |
verify HMAC - SHA256 signature and decrypt data with AES - CBC | def decrypt(self, data):
'''
verify HMAC-SHA256 signature and decrypt data with AES-CBC
'''
aes_key, hmac_key = self.keys
sig = data[-self.SIG_SIZE:]
data = data[:-self.SIG_SIZE]
if six.PY3 and not isinstance(data, bytes):
data = salt.utils.stringutils... |
Serialize and encrypt a python object | def dumps(self, obj):
'''
Serialize and encrypt a python object
'''
return self.encrypt(self.PICKLE_PAD + self.serial.dumps(obj)) |
Decrypt and un - serialize a python object | def loads(self, data, raw=False):
'''
Decrypt and un-serialize a python object
'''
data = self.decrypt(data)
# simple integrity check to verify that we got meaningful data
if not data.startswith(self.PICKLE_PAD):
return {}
load = self.serial.loads(data... |
Execute hiera and return the data | def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
conf):
'''
Execute hiera and return the data
'''
cmd = 'hiera -c {0}'.format(conf)
for key, val in six.iteritems(__grains__):
if isinstance(val, six.string_types):
cm... |
Gluster versions prior to 6 have a bug that requires tricking isatty. This adds gluster > to the output. Strip it off and produce clean xml for ElementTree. | def _gluster_output_cleanup(result):
'''
Gluster versions prior to 6 have a bug that requires tricking
isatty. This adds "gluster> " to the output. Strip it off and
produce clean xml for ElementTree.
'''
ret = ''
for line in result.splitlines():
if line.startswith('gluster>'):
... |
Perform a gluster -- xml command and log result. | def _gluster_xml(cmd):
'''
Perform a gluster --xml command and log result.
'''
# We will pass the command string as stdin to allow for much longer
# command strings. This is especially useful for creating large volumes
# where the list of bricks exceeds 128 characters.
if _get_version() < (3... |
Checks for python2. 6 or python2. 7 | def _iter(root, term):
'''
Checks for python2.6 or python2.7
'''
if sys.version_info < (2, 7):
return root.getiterator(term)
else:
return root.iter(term) |
Return peer status information | def peer_status():
'''
Return peer status information
The return value is a dictionary with peer UUIDs as keys and dicts of peer
information as values. Hostnames are listed in one list. GlusterFS separates
one of the hostnames but the only reason for this seems to be which hostname
happens to b... |
Add another node into the peer list. | def peer(name):
'''
Add another node into the peer list.
name
The remote host to probe.
CLI Example:
.. code-block:: bash
salt 'one.gluster.*' glusterfs.peer two
GLUSTER direct CLI example (to show what salt is sending to gluster):
$ gluster peer probe ftp2
GLU... |
Create a glusterfs volume | def create_volume(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False, arbiter=False):
'''
Create a glusterfs volume
name
Name of the gluster volume
bricks
Bricks to create volume from, in <peer>:<brick path> format. F... |
List configured volumes | def list_volumes():
'''
List configured volumes
CLI Example:
.. code-block:: bash
salt '*' glusterfs.list_volumes
'''
root = _gluster_xml('volume list')
if not _gluster_ok(root):
return None
results = [x.text for x in _iter(root, 'volume')]
return results |
Check the status of a gluster volume. | def status(name):
'''
Check the status of a gluster volume.
name
Volume name
CLI Example:
.. code-block:: bash
salt '*' glusterfs.status myvolume
'''
# Get volume status
root = _gluster_xml('volume status {0}'.format(name))
if not _gluster_ok(root):
# Most... |
.. versionadded:: 2015. 8. 4 | def info(name=None):
'''
.. versionadded:: 2015.8.4
Return gluster volume info.
name
Optional name to retrieve only information of one volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.info
'''
cmd = 'volume info'
if name is not None:
cmd += ' '... |
Start a gluster volume | def start_volume(name, force=False):
'''
Start a gluster volume
name
Volume name
force
Force the volume start even if the volume is started
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.start mycluster
'''
cmd = 'volu... |
Stop a gluster volume | def stop_volume(name, force=False):
'''
Stop a gluster volume
name
Volume name
force
Force stop the volume
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.stop_volume mycluster
'''
volinfo = info()
if name not in v... |
Deletes a gluster volume | def delete_volume(target, stop=True):
'''
Deletes a gluster volume
target
Volume to delete
stop : True
If ``True``, stop volume before delete
CLI Example:
.. code-block:: bash
salt '*' glusterfs.delete_volume <volume>
'''
volinfo = info()
if target not in... |
Add brick ( s ) to an existing volume | def add_volume_bricks(name, bricks):
'''
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.add_volume_bricks <volume> <bricks>
'''
volinfo = info()
if name ... |
Set quota to glusterfs volume. | def set_quota_volume(name, path, size, enable_quota=False):
'''
Set quota to glusterfs volume.
name
Name of the gluster volume
path
Folder path for restriction in volume ("/")
size
Hard-limit size of the volume (MB/GB)
enable_quota
Enable quota before set up r... |
Unset quota on glusterfs volume | def unset_quota_volume(name, path):
'''
Unset quota on glusterfs volume
name
Name of the gluster volume
path
Folder path for restriction in volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.unset_quota_volume <volume> <path>
'''
cmd = 'volume quota ... |
List quotas of glusterfs volume | def list_quota_volume(name):
'''
List quotas of glusterfs volume
name
Name of the gluster volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.list_quota_volume <volume>
'''
cmd = 'volume quota {0}'.format(name)
cmd += ' list'
root = _gluster_xml(cmd)
... |
.. versionadded:: 2019. 2. 0 | def get_op_version(name):
'''
.. versionadded:: 2019.2.0
Returns the glusterfs volume op-version
name
Name of the glusterfs volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.get_op_version <volume>
'''
cmd = 'volume get {0} cluster.op-version'.format(name)... |
.. versionadded:: 2019. 2. 0 | def get_max_op_version():
'''
.. versionadded:: 2019.2.0
Returns the glusterfs volume's max op-version value
Requires Glusterfs version > 3.9
CLI Example:
.. code-block:: bash
salt '*' glusterfs.get_max_op_version
'''
if _get_version() < (3, 10,):
return False, 'Gluste... |
.. versionadded:: 2019. 2. 0 | def set_op_version(version):
'''
.. versionadded:: 2019.2.0
Set the glusterfs volume op-version
version
Version to set the glusterfs volume op-version
CLI Example:
.. code-block:: bash
salt '*' glusterfs.set_op_version <volume>
'''
cmd = 'volume set all cluster.op-v... |
Check the version of Bower to ensure this module will work. Currently bower must be at least version 1. 3. | def _check_valid_version():
'''
Check the version of Bower to ensure this module will work. Currently
bower must be at least version 1.3.
'''
# pylint: disable=no-member
bower_version = _LooseVersion(
__salt__['cmd.run']('bower --version'))
valid_version = _LooseVersion('1.3')
# ... |
Create bower command line string | def _construct_bower_command(bower_command):
'''
Create bower command line string
'''
if not bower_command:
raise CommandExecutionError(
'bower_command, e.g. install, must be specified')
cmd = ['bower'] + shlex.split(bower_command)
cmd.extend(['--config.analytics', 'false',
... |
Install a Bower package. | def install(pkg,
dir,
pkgs=None,
runas=None,
env=None):
'''
Install a Bower package.
If no package is specified, the dependencies (from bower.json) of the
package in the given directory will be installed.
pkg
A package name in any format acce... |
Linux hosts using systemd 207 or later ignore/ etc/ sysctl. conf and only load from/ etc/ sysctl. d/ *. conf. This function will do the proper checks and return a default config file which will be valid for the Minion. Hosts running systemd > = 207 will use/ etc/ sysctl. d/ 99 - salt. conf. | def default_config():
'''
Linux hosts using systemd 207 or later ignore ``/etc/sysctl.conf`` and only
load from ``/etc/sysctl.d/*.conf``. This function will do the proper checks
and return a default config file which will be valid for the Minion. Hosts
running systemd >= 207 will use ``/etc/sysctl.d... |
Return a list of sysctl parameters for this minion | def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
config: Pull the data from the system configuration file
instead of the live data.
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
ret = {}
if config_file:
# If the ... |
Assign a single sysctl parameter for this minion | def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.ipv4.ip_forward 1
'''
value = six.text_type(value)
if six.PY3:
tran_tab = name.translate(''.maketrans('./', '/.'))
else:
... |
Assign and persist a simple sysctl parameter for this minion. If config is not specified a sensible default will be chosen using: mod: sysctl. default_config <salt. modules. linux_sysctl. default_config >. | def persist(name, value, config=None):
'''
Assign and persist a simple sysctl parameter for this minion. If ``config``
is not specified, a sensible default will be chosen using
:mod:`sysctl.default_config <salt.modules.linux_sysctl.default_config>`.
CLI Example:
.. code-block:: bash
s... |
Connect to a mongo database and read per - node pillar information. | def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
collection='pillar',
id_field='_id',
re_pattern=None,
re_replace='',
fields=None):
'''
Connect to a mongo database and read per-node pillar information.
Param... |
If this XML tree has an xmlns attribute then etree will add it to the beginning of the tag like: { http:// path } tag. | def _conv_name(x):
'''
If this XML tree has an xmlns attribute, then etree will add it
to the beginning of the tag, like: "{http://path}tag".
'''
if '}' in x:
comps = x.split('}')
name = comps[1]
return name
return x |
Converts an XML ElementTree to a dictionary that only contains items. This is the default behavior in version 2017. 7. This will default to prevent unexpected parsing issues on modules dependant on this. | def _to_dict(xmltree):
'''
Converts an XML ElementTree to a dictionary that only contains items.
This is the default behavior in version 2017.7. This will default to prevent
unexpected parsing issues on modules dependant on this.
'''
# If this object has no children, the for..loop below will ret... |
Returns the full XML dictionary including attributes. | def _to_full_dict(xmltree):
'''
Returns the full XML dictionary including attributes.
'''
xmldict = {}
for attrName, attrValue in xmltree.attrib.items():
xmldict[attrName] = attrValue
if not xmltree.getchildren():
if not xmldict:
# If we don't have attributes, we sh... |
No - op state to support state config via the stateconf renderer. | def _no_op(name, **kwargs):
'''
No-op state to support state config via the stateconf renderer.
'''
return dict(name=name, result=True, changes={}, comment='') |
Helper for deriving the current state of the container from the inspect results. | def _get_state(inspect_results):
'''
Helper for deriving the current state of the container from the inspect
results.
'''
if inspect_results.get('State', {}).get('Paused', False):
return 'paused'
elif inspect_results.get('State', {}).get('Running', False):
return 'running'
el... |
Decorator to run a function that requires the use of a docker. Client () instance. | def _docker_client(wrapped):
'''
Decorator to run a function that requires the use of a docker.Client()
instance.
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
'''
Ensure that the client is present
'''
kwargs = __utils__['args.clean_kwargs'](**kwargs... |
Decorator to trigger a refresh of salt mine data. | def _refresh_mine_cache(wrapped):
'''
Decorator to trigger a refresh of salt mine data.
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
'''
refresh salt mine on exit.
'''
returned = wrapped(*args, **__utils__['args.clean_kwargs'](**kwargs))
if _che... |
Change the state of a container | def _change_state(name, action, expected, *args, **kwargs):
'''
Change the state of a container
'''
pre = state(name)
if action != 'restart' and pre == expected:
return {'result': False,
'state': {'old': expected, 'new': expected},
'comment': ('Container \'{0}... |
Get the MD5 checksum of a file from a container | def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name,
'md5sum {0}'.format(pipes.quote(path)),
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination ... |
Get the method to be used in shell commands | def _get_exec_driver():
'''
Get the method to be used in shell commands
'''
contextkey = 'docker.exec_driver'
if contextkey not in __context__:
from_config = __salt__['config.get'](contextkey, None)
# This if block can be removed once we make docker-exec a default
# option, a... |
Returns a list of the top - level images ( those which are not parents ). If subset ( an iterable ) is passed the top - level images in the subset will be returned otherwise all top - level images will be returned. | def _get_top_level_images(imagedata, subset=None):
'''
Returns a list of the top-level images (those which are not parents). If
``subset`` (an iterable) is passed, the top-level images in the subset will
be returned, otherwise all top-level images will be returned.
'''
try:
parents = [im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.