desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Return keypair object for the minion.
:rtype: Crypto.PublicKey.RSA._RSAobj
:return: The RSA keypair'
| def get_keys(self):
| user = self.opts.get(u'user', u'root')
salt.utils.verify.check_path_traversal(self.opts[u'pki_dir'], user)
if os.path.exists(self.rsa_path):
with salt.utils.files.fopen(self.rsa_path) as f:
key = RSA.importKey(f.read())
log.debug(u'Loaded minion key: %s', self.rsa_path)
... |
'Encrypt a string with the minion private key to verify identity
with the master.
:param str clear_tok: A plaintext token to encrypt
:return: Encrypted token
:rtype: str'
| def gen_token(self, clear_tok):
| return private_encrypt(self.get_keys(), clear_tok)
|
'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'
| def minion_sign_in_payload(self):
| payload = {}
payload[u'cmd'] = u'_auth'
payload[u'id'] = self.opts[u'id']
try:
pubkey_path = os.path.join(self.opts[u'pki_dir'], self.mpub)
with salt.utils.files.fopen(pubkey_path) as f:
pub = RSA.importKey(f.read())
cipher = PKCS1_OAEP.new(pub)
payload[u'toke... |
'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
:param dict payload: The incoming payload. This is a dictionary which may have the following keys:
\'... | def decrypt_aes(self, payload, master_pub=True):
| if self.opts.get(u'auth_trb', False):
log.warning(u'Auth Called: %s', u''.join(traceback.format_stack()))
else:
log.debug(u'Decrypting the current master AES key')
key = self.get_keys()
cipher = PKCS1_OAEP.new(key)
key_str = cipher.decrypt(payload[u'aes'])
if... |
'Wraps the verify_signature method so we have
additional checks.
:rtype: bool
:return: Success or failure of public key verification'
| def verify_pubkey_sig(self, message, sig):
| if self.opts[u'master_sign_key_name']:
path = os.path.join(self.opts[u'pki_dir'], (self.opts[u'master_sign_key_name'] + u'.pub'))
if os.path.isfile(path):
res = verify_signature(path, message, binascii.a2b_base64(sig))
else:
log.error(u'Verification public key ... |
'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 key
\'enc\': The format of the message. (\'clear\', \'pub\', \'aes\')
\'publish_por... | def check_auth_deps(self, payload):
| if ((u'pub_sig' in payload) and self.opts[u'verify_master_pubkey_sign']):
return True
elif ((u'pub_sig' not in payload) and (not self.opts[u'verify_master_pubkey_sign'])):
return True
elif ((u'pub_sig' in payload) and (not self.opts[u'verify_master_pubkey_sign'])):
log.error(u'The ... |
'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
\'enc\': The format of the message. (\'clear\', \'pub\', etc)
\'publish_port\': The TCP port w... | def extract_aes(self, payload, master_pub=True):
| if master_pub:
try:
(aes, token) = self.decrypt_aes(payload, master_pub)
if (token != self.token):
log.error(u'The master failed to decrypt the random minion token')
return u''
except Exception:
log.error(u'T... |
'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 the message. (\'clear\', \'pub\', etc)
\'publish_port\': The TCP port which published the message
\'... | def verify_master(self, payload, master_pub=True):
| m_pub_fn = os.path.join(self.opts[u'pki_dir'], self.mpub)
m_pub_exists = os.path.isfile(m_pub_fn)
if (m_pub_exists and master_pub and (not self.opts[u'open_mode'])):
with salt.utils.files.fopen(m_pub_fn) as fp_:
local_master_pub = fp_.read()
if (payload[u'pub_key'].replace(u'\n',... |
'Only create one instance of SAuth per __key()'
| def __new__(cls, opts, io_loop=None):
| key = cls.__key(opts)
auth = SAuth.instances.get(key)
if (auth is None):
log.debug(u'Initializing new SAuth for %s', key)
auth = object.__new__(cls)
auth.__singleton_init__(opts)
SAuth.instances[key] = auth
else:
log.debug(u'Re-using SAuth for ... |
'Init an Auth instance
:param dict opts: Options for this server
:return: Auth instance
:rtype: Auth'
| def __singleton_init__(self, opts, io_loop=None):
| self.opts = opts
if six.PY2:
self.token = Crypticle.generate_key_string()
else:
self.token = salt.utils.stringutils.to_bytes(Crypticle.generate_key_string())
self.serial = salt.payload.Serial(self.opts)
self.pub_path = os.path.join(self.opts[u'pki_dir'], u'minion.pub')
self.rsa_p... |
'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
:returns: A crypticle used for encryption operations'
| def authenticate(self, _=None):
| acceptance_wait_time = self.opts[u'acceptance_wait_time']
acceptance_wait_time_max = self.opts[u'acceptance_wait_time_max']
channel = salt.transport.client.ReqChannel.factory(self.opts, crypt=u'clear')
if (not acceptance_wait_time_max):
acceptance_wait_time_max = acceptance_wait_time
while T... |
'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: Number of seconds to wait before timing out the sign-in request
:param bool safe: If True, do not raise an excepti... | def sign_in(self, timeout=60, safe=True, tries=1, channel=None):
| auth = {}
auth_timeout = self.opts.get(u'auth_timeout', None)
if (auth_timeout is not None):
timeout = auth_timeout
auth_safemode = self.opts.get(u'auth_safemode', None)
if (auth_safemode is not None):
safe = auth_safemode
auth_tries = self.opts.get(u'auth_tries', None)
if (a... |
'encrypt data with AES-CBC and sign it with HMAC-SHA256'
| def encrypt(self, data):
| (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 + salt.utils.stringutils.to_bytes((pad * chr(pad))))
iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
cypher = AES.new(aes_key... |
'verify HMAC-SHA256 signature and decrypt data with AES-CBC'
| def decrypt(self, data):
| (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.to_bytes(data)
mac_bytes = hmac.new(hmac_key, data, hashlib.sha256).digest()
if (len(mac_bytes) != len(sig)):
... |
'Serialize and encrypt a python object'
| def dumps(self, obj):
| return self.encrypt((self.PICKLE_PAD + self.serial.dumps(obj)))
|
'Decrypt and un-serialize a python object'
| def loads(self, data, raw=False):
| data = self.decrypt(data)
if (not data.startswith(self.PICKLE_PAD)):
return {}
load = self.serial.loads(data[len(self.PICKLE_PAD):], raw=raw)
return load
|
'Generate filenames in path that satisfy criteria specified in
the constructor.
This method is a generator and should be repeatedly called
until there are no more results.'
| def find(self, path):
| if (self.mindepth < 1):
(dirpath, name) = os.path.split(path)
(match, fstat) = self._check_criteria(dirpath, name, path)
if match:
for result in self._perform_actions(path, fstat=fstat):
(yield result)
for (dirpath, dirs, files) in os.walk(path):
relpa... |
'error(msg : string)
Print a usage message incorporating \'msg\' to stderr and exit.
This keeps option parsing exit status uniform for all parsing errors.'
| def error(self, msg):
| self.print_usage(sys.stderr)
self.exit(salt.defaults.exitcodes.EX_USAGE, '{0}: error: {1}\n'.format(self.get_prog_name(), msg))
|
'Report whether a pidfile exists'
| def check_pidfile(self):
| from salt.utils.process import check_pidfile
return check_pidfile(self.config['pidfile'])
|
'Return a pid contained in a pidfile'
| def get_pidfile(self):
| from salt.utils.process import get_pidfile
return get_pidfile(self.config['pidfile'])
|
'Check if a pid file exists and if it is associated with
a running process.'
| def check_running(self):
| if self.check_pidfile():
pid = self.get_pidfile()
if (not salt.utils.platform.is_windows()):
if (self.check_pidfile() and self.is_daemonized(pid) and (not (os.getppid() == pid))):
return True
elif (self.check_pidfile() and self.is_daemonized(pid)):
ret... |
'Returns true if local RAET Minion is available'
| def _find_raet_minion(self, opts):
| yardname = 'manor'
dirpath = opts['sock_dir']
role = opts.get('id')
if (not role):
emsg = 'Missing role required to setup RAET SaltCaller.'
logging.getLogger(__name__).error((emsg + '\n'))
raise ValueError(emsg)
kind = opts.get('__role')
if (kind not in ... |
'The decorator is instantiated with a list of dependencies (string of
global name)
An example use of this would be:
@depends(\'modulename\')
def test():
return \'foo\'
OR
@depends(\'modulename\', fallback_function=function)
def test():
return \'foo\''
| def __init__(self, *dependencies, **kwargs):
| log.trace('Depends decorator instantiated with dep list of {0}'.format(dependencies))
self.dependencies = dependencies
self.fallback_function = kwargs.get('fallback_function')
|
'The decorator is "__call__"d with the function, we take that function
and determine which module and function name it is to store in the
class wide depandancy_dict'
| def __call__(self, function):
| try:
frame = inspect.stack()[1][0]
(_, kind, mod_name) = frame.f_globals['__name__'].rsplit('.', 2)
fun_name = function.__name__
for dep in self.dependencies:
self.dependency_dict[kind][dep][(mod_name, fun_name)] = (frame, self.fallback_function)
except Exception as e... |
'This is a class global method to enforce the dependencies that you
currently know about.
It will modify the "functions" dict and remove/replace modules that
are missing dependencies.'
| @classmethod
def enforce_dependencies(cls, functions, kind):
| for (dependency, dependent_dict) in six.iteritems(cls.dependency_dict[kind]):
for ((mod_name, func_name), (frame, fallback_function)) in six.iteritems(dependent_dict):
if (dependency is True):
log.trace('Dependency for {0}.{1} exists, not unloading'.format(mod_name... |
'Constructor.
:param globals: Module globals. Important for finding out replacement functions
:param version: Expiration version
:return:'
| def __init__(self, globals, version):
| from salt.version import SaltStackVersion, __saltstack_version__
self._globals = globals
self._exp_version_name = version
self._exp_version = SaltStackVersion.from_name(self._exp_version_name)
self._curr_version = __saltstack_version__.info
self._raise_later = None
self._function = None
... |
'Extract function-specific keywords from all of the kwargs.
:param kwargs:
:return:'
| def _get_args(self, kwargs):
| _args = list()
_kwargs = dict()
if ('__pub_arg' in kwargs):
for arg_item in kwargs.get('__pub_arg', list()):
if (type(arg_item) == dict):
_kwargs.update(arg_item.copy())
else:
_args.append(arg_item)
else:
_kwargs = kwargs.copy()
... |
'Call target function that has been decorated.
:return:'
| def _call_function(self, kwargs):
| if self._raise_later:
raise self._raise_later
if self._function:
(args, kwargs) = self._get_args(kwargs)
try:
return self._function(*args, **kwargs)
except TypeError as error:
error = str(error).replace(self._function, self._orig_f_name)
log.er... |
'Callable method of the decorator object when
the decorated function is gets called.
:param function:
:return:'
| def __call__(self, function):
| self._function = function
self._orig_f_name = self._function.__name__
|
'Constructor of the decorator \'is_deprecated\'.
:param globals: Module globals
:param version: Version to be deprecated
:param with_successor: Successor function (optional)
:return:'
| def __init__(self, globals, version, with_successor=None):
| _DeprecationDecorator.__init__(self, globals, version)
self._successor = with_successor
|
'Callable method of the decorator object when
the decorated function is gets called.
:param function:
:return:'
| def __call__(self, function):
| _DeprecationDecorator.__call__(self, function)
def _decorate(*args, **kwargs):
'\n Decorator function.\n\n :param args:\n :param kwargs:\n ... |
'Constructor of the decorator \'with_deprecated\'
:param globals:
:param version:
:param with_name:
:param policy:
:return:'
| def __init__(self, globals, version, with_name=None, policy=_DeprecationDecorator.OPT_OUT):
| _DeprecationDecorator.__init__(self, globals, version)
self._with_name = with_name
self._policy = policy
|
'Based on the configuration, set to execute an old or a new function.
:return:'
| def _set_function(self, function):
| full_name = '{m_name}.{f_name}'.format(m_name=(self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[(-1)]), f_name=function.__name__)
if full_name.startswith('.'):
self._raise_later = CommandExecutionError('Module not found for function "{f_name}"'.format(f_name... |
'Returns True, if a component configuration explicitly is
asking to use an old version of the deprecated function.
:return:'
| def _is_used_deprecated(self):
| func_path = '{m_name}.{f_name}'.format(m_name=(self._globals.get(self.MODULE_NAME, '') or self._globals['__name__'].split('.')[(-1)]), f_name=self._orig_f_name)
return (((func_path in self._globals.get('__opts__').get(self.CFG_USE_DEPRECATED, list())) or (func_path in self._globals.get('__pillar__').get(self.CF... |
'Callable method of the decorator object when
the decorated function is gets called.
:param function:
:return:'
| def __call__(self, function):
| _DeprecationDecorator.__call__(self, function)
def _decorate(*args, **kwargs):
'\n Decorator function.\n\n :param args:\n :param kwargs:\n ... |
''
| def __init__(self, name=None):
| self.name = name
|
''
| def __call__(self, function):
| name = (self.name or function.__name__)
if (name not in self.salt_jinja_filters):
log.debug(u"Marking '%s' as a jinja filter", name)
self.salt_jinja_filters[name] = function
return function
|
''
| def __init__(self, name=None):
| self.name = name
|
''
| def __call__(self, function):
| name = (self.name or function.__name__)
if (name not in self.salt_jinja_tests):
log.debug("Marking '%s' as a jinja test", name)
self.salt_jinja_tests[name] = function
return function
|
''
| def __init__(self, name=None):
| self.name = name
|
''
| def __call__(self, function):
| name = (self.name or function.__name__)
if (name not in self.salt_jinja_globals):
log.debug('Marking "{0}" as a jinja global'.format(name))
self.salt_jinja_globals[name] = function
return function
|
'Context management protocol. Returns self.'
| def __enter__(self):
| return self
|
'Context management protocol. Calls close()'
| def __exit__(self, *args):
| self.close()
|
'Setup and return file_client'
| def file_client(self):
| if (not self._file_client):
self._file_client = salt.fileclient.get_file_client(self.opts, self.pillar_rend)
return self._file_client
|
'When an object is called it is being used as a requisite'
| def __call__(self, id_, requisite='require'):
| return StateRequisite(requisite, self.module, id_)
|
'Init an RSAX931Signer instance
:param str keydata: The RSA private key in PEM format'
| def __init__(self, keydata):
| keydata = salt.utils.stringutils.to_bytes(keydata, 'ascii')
self._bio = libcrypto.BIO_new_mem_buf(keydata, len(keydata))
self._rsa = c_void_p(libcrypto.RSA_new())
if (not libcrypto.PEM_read_bio_RSAPrivateKey(self._bio, pointer(self._rsa), None, None)):
raise ValueError('invalid RSA private... |
'Sign a message (digest) using the private key
:param str msg: The message (digest) to sign
:rtype: str
:return: The signature, or an empty string if the encryption failed'
| def sign(self, msg):
| buf = create_string_buffer(libcrypto.RSA_size(self._rsa))
msg = salt.utils.stringutils.to_bytes(msg)
size = libcrypto.RSA_private_encrypt(len(msg), msg, buf, self._rsa, RSA_X931_PADDING)
if (size < 0):
raise ValueError('Unable to encrypt message')
return buf[0:size]
|
'Init an RSAX931Verifier instance
:param str pubdata: The RSA public key in PEM format'
| def __init__(self, pubdata):
| pubdata = salt.utils.stringutils.to_bytes(pubdata, 'ascii')
pubdata = pubdata.replace(six.b('RSA '), six.b(''))
self._bio = libcrypto.BIO_new_mem_buf(pubdata, len(pubdata))
self._rsa = c_void_p(libcrypto.RSA_new())
if (not libcrypto.PEM_read_bio_RSA_PUBKEY(self._bio, pointer(self._rsa), None, Non... |
'Recover the message (digest) from the signature using the public key
:param str signed: The signature created with the private key
:rtype: str
:return: The message (digest) recovered from the signature, or an empty
string if the decryption failed'
| def verify(self, signed):
| buf = create_string_buffer(libcrypto.RSA_size(self._rsa))
signed = salt.utils.stringutils.to_bytes(signed)
size = libcrypto.RSA_public_decrypt(len(signed), signed, buf, self._rsa, RSA_X931_PADDING)
if (size < 0):
raise ValueError('Unable to decrypt message')
return buf[0:size]
|
'Initialize the updates collection. Can be accessed via
``Updates.updates``'
| def __init__(self):
| self.updates = win32com.client.Dispatch('Microsoft.Update.UpdateColl')
|
'Return how many records are in the Microsoft Update Collection
Returns:
int: The number of updates in the collection
Code Example:
.. code-block:: python
import salt.utils.win_update
updates = salt.utils.win_update.Updates()
updates.count()'
| def count(self):
| return self.updates.Count
|
'Create a dictionary with the details for the updates in the collection.
Returns:
dict: Details about each update
.. code-block:: cfg
List of Updates:
{\'<GUID>\': {\'Title\': <title>,
\'KB\': <KB>,
\'GUID\': <the globally unique identifier for the update>
\'Description\': <description>,
\'Downloaded\': <has the update... | def list(self):
| if (self.count() == 0):
return 'Nothing to return'
log.debug('Building a detailed report of the results.')
results = {}
for update in self.updates:
results[update.Identity.UpdateID] = {'guid': update.Identity.UpdateID, 'Title': str(update.Title), 'Type': self.upda... |
'Create a dictionary with a summary of the updates in the collection.
Returns:
dict: Summary of the contents of the collection
.. code-block:: cfg
Summary of Updates:
{\'Total\': <total number of updates returned>,
\'Available\': <updates that are not downloaded or installed>,
\'Downloaded\': <updates that are download... | def summary(self):
| if (self.count() == 0):
return 'Nothing to return'
results = {'Total': 0, 'Available': 0, 'Downloaded': 0, 'Installed': 0, 'Categories': {}, 'Severity': {}}
for update in self.updates:
results['Total'] += 1
if ((not salt.utils.is_true(update.IsDownloaded)) and (not salt.utils.i... |
'Initialize the session and load all updates into the ``_updates``
collection. This collection is used by the other class functions instead
of querying Windows update (expensive).
Need to look at the possibility of loading this into ``__context__``'
| def __init__(self):
| pythoncom.CoInitialize()
self._session = win32com.client.Dispatch('Microsoft.Update.Session')
self._updates = win32com.client.Dispatch('Microsoft.Update.UpdateColl')
self.refresh()
|
'Get the contents of ``_updates`` (all updates) and puts them in an
Updates class to expose the list and summary functions.
Returns:
Updates: An instance of the Updates class with all updates for the
system.
.. code-block:: python
import salt.utils.win_update
wua = salt.utils.win_update.WindowsUpdateAgent()
updates = w... | def updates(self):
| updates = Updates()
found = updates.updates
for update in self._updates:
found.Add(update)
return updates
|
'Refresh the contents of the ``_updates`` collection. This gets all
updates in the Windows Update system and loads them into the collection.
This is the part that is slow.
Code Example:
.. code-block:: python
import salt.utils.win_update
wua = salt.utils.win_update.WindowsUpdateAgent()
wua.refresh()'
| def refresh(self):
| search_string = "Type='Software' or Type='Driver'"
searcher = self._session.CreateUpdateSearcher()
self._session.ClientApplicationID = 'Salt: Load Updates'
try:
results = searcher.Search(search_string)
if (results.Updates.Count == 0):
log.debug('No Updates f... |
'Gets a list of all updates available on the system that match the passed
criteria.
Args:
skip_hidden (bool): Skip hidden updates. Default is True
skip_installed (bool): Skip installed updates. Default is True
skip_mandatory (bool): Skip mandatory updates. Default is False
skip_reboot (bool): Skip updates that can or d... | def available(self, skip_hidden=True, skip_installed=True, skip_mandatory=False, skip_reboot=False, software=True, drivers=True, categories=None, severities=None):
| updates = Updates()
found = updates.updates
for update in self._updates:
if (salt.utils.is_true(update.IsHidden) and skip_hidden):
continue
if (salt.utils.is_true(update.IsInstalled) and skip_installed):
continue
if (salt.utils.is_true(update.IsMandatory) and ... |
'Search for either a single update or a specific list of updates. GUIDs
are searched first, then KB numbers, and finally Titles.
Args:
search_string (str, list): The search string to use to find the
update. This can be the GUID or KB of the update (preferred). It can
also be the full Title of the update or any part of ... | def search(self, search_string):
| updates = Updates()
found = updates.updates
if isinstance(search_string, six.string_types):
search_string = [search_string]
if isinstance(search_string, six.integer_types):
search_string = [str(search_string)]
for update in self._updates:
for find in search_string:
... |
'Download the updates passed in the updates collection. Load the updates
collection using ``search`` or ``available``
Args:
updates (Updates): An instance of the Updates class containing a
the updates to be downloaded.
Returns:
dict: A dictionary containing the results of the download
Code Example:
.. code-block:: pyth... | def download(self, updates):
| if (updates.count() == 0):
ret = {'Success': False, 'Updates': 'Nothing to download'}
return ret
downloader = self._session.CreateUpdateDownloader()
self._session.ClientApplicationID = 'Salt: Download Update'
download_list = win32com.client.Dispatch('Microsoft.Update.UpdateCo... |
'Install the updates passed in the updates collection. Load the updates
collection using the ``search`` or ``available`` functions. If the
updates need to be downloaded, use the ``download`` function.
Args:
updates (Updates): An instance of the Updates class containing a
the updates to be installed.
Returns:
dict: A di... | def install(self, updates):
| if (updates.count() == 0):
ret = {'Success': False, 'Updates': 'Nothing to install'}
return ret
installer = self._session.CreateUpdateInstaller()
self._session.ClientApplicationID = 'Salt: Install Update'
install_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')
... |
'Uninstall the updates passed in the updates collection. Load the updates
collection using the ``search`` or ``available`` functions.
.. note:: Starting with Windows 10 the Windows Update Agent is unable to
uninstall updates. An ``Uninstall Not Allowed`` error is returned. If
this error is encountered this function wil... | def uninstall(self, updates):
| if (updates.count() == 0):
ret = {'Success': False, 'Updates': 'Nothing to uninstall'}
return ret
installer = self._session.CreateUpdateInstaller()
self._session.ClientApplicationID = 'Salt: Install Update'
uninstall_list = win32com.client.Dispatch('Microsoft.Update.UpdateCol... |
'Internal function for running commands. Used by the uninstall function.
Args:
cmd (str, list): The command to run
Returns:
str: The stdout of the command'
| def _run(self, cmd):
| if isinstance(cmd, six.string_types):
cmd = salt.utils.args.shlex_split(cmd)
try:
log.debug(cmd)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p.communicate()
except (OSError, IOError) as exc:
log.debug('Command Failed... |
'Create a processes and args + kwargs
This will deterimine if it is a Process class, otherwise it assumes
it is a function'
| def add_process(self, tgt, args=None, kwargs=None, name=None):
| if (args is None):
args = []
if (kwargs is None):
kwargs = {}
if salt.utils.platform.is_windows():
if ((type(MultiprocessingProcess) is type(tgt)) and issubclass(tgt, MultiprocessingProcess)):
need_log_queue = True
else:
need_log_queue = False
... |
'Create new process (assuming this one is dead), then remove the old one'
| def restart_process(self, pid):
| if (self._restart_processes is False):
return
log.info('Process {0} ({1}) died with exit status {2}, restarting...'.format(self._process_map[pid]['tgt'], pid, self._process_map[pid]['Process'].exitcode))
self._process_map[pid]['Process'].join(1)
self.add_process(self._pro... |
'Load and start all available api modules'
| @gen.coroutine
def run(self, async=False):
| log.debug('Process Manager starting!')
salt.utils.appendproctitle(self.name)
if (signal.getsignal(signal.SIGTERM) is signal.SIG_DFL):
signal.signal(signal.SIGTERM, self.kill_children)
if (signal.getsignal(signal.SIGINT) is signal.SIG_DFL):
signal.signal(signal.SIGINT, self.kill_chi... |
'Check the children once'
| def check_children(self):
| if (self._restart_processes is True):
for (pid, mapping) in six.iteritems(self._process_map):
if (not mapping['Process'].is_alive()):
log.trace('Process restart of {0}'.format(pid))
self.restart_process(pid)
|
'Kill all of the children'
| def kill_children(self, *args, **kwargs):
| signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
if (os.getpid() != self._pid):
if callable(self._sigterm_handler):
return self._sigterm_handler(*args)
elif (self._sigterm_handler is not None):
return signal.default_int_handle... |
'Return the names of remote refs (stripped of the remote name) and tags
which are map to the branches and tags.'
| def _get_envs_from_ref_paths(self, refs):
| def _check_ref(env_set, rname):
'\n Add the appropriate saltenv(s) to the set\n '
if (rname in self.saltenv_revmap):
env_set.update(self.saltenv_revmap[rname])
else:
... |
'Programatically determine config value based on the desired saltenv'
| @classmethod
def add_conf_overlay(cls, name):
| def _getconf(self, tgt_env='base'):
strip_sep = (lambda x: (x.rstrip(os.sep) if (name in ('root', 'mountpoint')) else x))
if (self.role != 'gitfs'):
return strip_sep(getattr(self, ('_' + name)))
saltenv_conf = self.saltenv.get(tgt_env, {})
if (name == 'ref'):
... |
'This function must be overridden in a sub-class'
| def add_refspecs(self, *refspecs):
| raise NotImplementedError()
|
'Check if the relative root path exists in the checked-out copy of the
remote. Return the full path to that relative root if it does exist,
otherwise return None.'
| def check_root(self):
| root_dir = salt.utils.path.join(self.cachedir, self.root()).rstrip(os.sep)
if os.path.isdir(root_dir):
return root_dir
log.error("Root path '%s' not present in %s remote '%s', skipping.", self.root, self.role, self.id)
return None
|
'Remove stale refs so that they are no longer seen as fileserver envs'
| def clean_stale_refs(self):
| cleaned = []
cmd_str = 'git remote prune origin'
cmd = subprocess.Popen(shlex.split(cmd_str), close_fds=(not salt.utils.platform.is_windows()), cwd=os.path.dirname(self.gitdir), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = cmd.communicate()[0]
if six.PY3:
output = outp... |
'Clear update.lk'
| def clear_lock(self, lock_type='update'):
| lock_file = self._get_lock_file(lock_type=lock_type)
def _add_error(errlist, exc):
msg = 'Unable to remove update lock for {0} ({1}): {2} '.format(self.url, lock_file, exc)
log.debug(msg)
errlist.append(msg)
success = []
failed = []
try:
os.... |
'Ensure that the configured refspecs are set'
| def configure_refspecs(self):
| try:
refspecs = set(self.get_refspecs())
except (git.exc.GitCommandError, GitRemoteError) as exc:
log.error("Failed to get refspecs for %s remote '%s': %s", self.role, self.id, exc)
return
desired_refspecs = set(self.refspecs)
to_delete = ((refspecs - desi... |
'Fetch the repo. If the local copy was updated, return True. If the
local copy was already up-to-date, return False.
This function requires that a _fetch() function be implemented in a
sub-class.'
| def fetch(self):
| try:
with self.gen_lock(lock_type='update'):
log.debug("Fetching %s remote '%s'", self.role, self.id)
return self._fetch()
except GitLockError as exc:
if (exc.errno == errno.EEXIST):
log.warning("Update lock file is present for %s ... |
'Place a lock file if (and only if) it does not already exist.'
| def _lock(self, lock_type='update', failhard=False):
| try:
fh_ = os.open(self._get_lock_file(lock_type), ((os.O_CREAT | os.O_EXCL) | os.O_WRONLY))
with os.fdopen(fh_, 'w'):
os.write(fh_, six.b(str(os.getpid())))
except (OSError, IOError) as exc:
if (exc.errno == errno.EEXIST):
with salt.utils.files.fopen(self._get_lo... |
'Place an lock file and report on the success/failure. This is an
interface to be used by the fileserver runner, so it is hard-coded to
perform an update lock. We aren\'t using the gen_lock()
contextmanager here because the lock is meant to stay and not be
automatically removed.'
| def lock(self):
| success = []
failed = []
try:
result = self._lock(lock_type='update')
except GitLockError as exc:
failed.append(exc.strerror)
else:
if (result is not None):
success.append(result)
return (success, failed)
|
'Set and automatically clear a lock'
| @contextlib.contextmanager
def gen_lock(self, lock_type='update'):
| lock_set = False
try:
self._lock(lock_type=lock_type, failhard=True)
lock_set = True
(yield)
except (OSError, IOError, GitLockError) as exc:
raise GitLockError(exc.errno, exc.strerror)
finally:
if lock_set:
self.clear_lock(lock_type=lock_type)
|
'This function must be overridden in a sub-class'
| def init_remote(self):
| raise NotImplementedError()
|
'This function must be overridden in a sub-class'
| def checkout(self):
| raise NotImplementedError()
|
'This function must be overridden in a sub-class'
| def dir_list(self, tgt_env):
| raise NotImplementedError()
|
'Check if an environment is exposed by comparing it against a whitelist
and blacklist.'
| def env_is_exposed(self, tgt_env):
| return salt.utils.check_whitelist_blacklist(tgt_env, whitelist=self.saltenv_whitelist, blacklist=self.saltenv_blacklist)
|
'Provider-specific code for fetching, must be implemented in a
sub-class.'
| def _fetch(self):
| raise NotImplementedError()
|
'This function must be overridden in a sub-class'
| def envs(self):
| raise NotImplementedError()
|
'This function must be overridden in a sub-class'
| def file_list(self, tgt_env):
| raise NotImplementedError()
|
'This function must be overridden in a sub-class'
| def find_file(self, path, tgt_env):
| raise NotImplementedError()
|
'Resolve dynamically-set branch'
| def get_checkout_target(self):
| if (self.branch == '__env__'):
target = (self.opts.get('pillarenv') or self.opts.get('environment') or 'base')
return (self.opts['{0}_base'.format(self.role)] if (target == 'base') else target)
return self.branch
|
'This function must be overridden in a sub-class'
| def get_refspecs(self):
| raise NotImplementedError()
|
'Return a tree object for the specified environment'
| def get_tree(self, tgt_env):
| if (not self.env_is_exposed(tgt_env)):
return None
tgt_ref = self.ref(tgt_env)
if (tgt_ref is None):
return None
for ref_type in self.ref_types:
try:
func_name = 'get_tree_from_{0}'.format(ref_type)
func = getattr(self, func_name)
except AttributeE... |
'Examine self.id and assign self.url (and self.branch, for git_pillar)'
| def get_url(self):
| if (self.role in ('git_pillar', 'winrepo')):
try:
(self.branch, self.url) = self.id.split(None, 1)
except ValueError:
self.branch = self.opts['{0}_branch'.format(self.role)]
self.url = self.id
else:
self.url = self.id
|
'Only needed in pygit2, included in the base class for simplicty of use'
| def setup_callbacks(self):
| pass
|
'Override this function in a sub-class to implement auth checking.'
| def verify_auth(self):
| self.credentials = None
return True
|
'This function must be overridden in a sub-class'
| def write_file(self, blob, dest):
| raise NotImplementedError()
|
'Add the specified refspecs to the "origin" remote'
| def add_refspecs(self, *refspecs):
| for refspec in refspecs:
try:
self.repo.git.config('--add', 'remote.origin.fetch', refspec)
log.debug("Added refspec '%s' to %s remote '%s'", refspec, self.role, self.id)
except git.exc.GitCommandError as exc:
log.error("Failed to add re... |
'Checkout the configured branch/tag. We catch an "Exception" class here
instead of a specific exception class because the exceptions raised by
GitPython when running these functions vary in different versions of
GitPython.'
| def checkout(self):
| tgt_ref = self.get_checkout_target()
try:
head_sha = self.repo.rev_parse('HEAD').hexsha
except Exception:
head_sha = None
for (rev_parse_target, checkout_ref) in ((('origin/' + tgt_ref), ('origin/' + tgt_ref)), (('tags/' + tgt_ref), ('tags/' + tgt_ref))):
try:
target_... |
'Initialize/attach to a remote using GitPython. Return a boolean
which will let the calling function know whether or not a new repo was
initialized by this function.'
| def init_remote(self):
| new = False
if (not os.listdir(self.cachedir)):
self.repo = git.Repo.init(self.cachedir)
new = True
else:
try:
self.repo = git.Repo(self.cachedir)
except git.exc.InvalidGitRepositoryError:
log.error(_INVALID_REPO.format(self.cachedir, self.url, self.ro... |
'Get list of directories for the target environment using GitPython'
| def dir_list(self, tgt_env):
| ret = set()
tree = self.get_tree(tgt_env)
if (not tree):
return ret
if self.root(tgt_env):
try:
tree = (tree / self.root(tgt_env))
except KeyError:
return ret
relpath = (lambda path: os.path.relpath(path, self.root(tgt_env)))
else:
relp... |
'Check the refs and return a list of the ones which can be used as salt
environments.'
| def envs(self):
| ref_paths = [x.path for x in self.repo.refs]
return self._get_envs_from_ref_paths(ref_paths)
|
'Fetch the repo. If the local copy was updated, return True. If the
local copy was already up-to-date, return False.'
| def _fetch(self):
| origin = self.repo.remotes[0]
try:
fetch_results = origin.fetch()
except AssertionError:
fetch_results = origin.fetch()
new_objs = False
for fetchinfo in fetch_results:
if (fetchinfo.old_commit is not None):
log.debug("%s has updated '%s' for remote... |
'Get file list for the target environment using GitPython'
| def file_list(self, tgt_env):
| files = set()
symlinks = {}
tree = self.get_tree(tgt_env)
if (not tree):
return (files, symlinks)
if self.root(tgt_env):
try:
tree = (tree / self.root(tgt_env))
except KeyError:
return (files, symlinks)
relpath = (lambda path: os.path.relpath(p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.