INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Ensure that the named database is absent name The name of the database to remove
def absent(name, **connection_args): ''' Ensure that the named database is absent name The name of the database to remove ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if db exists and remove it if __salt__['mysql.db_...
Return the net.find runner options.
def _get_net_runner_opts(): ''' Return the net.find runner options. ''' runner_opts = __opts__.get('runners', {}).get('net.find', {}) return { 'target': runner_opts.get('target', _DEFAULT_TARGET), 'expr_form': runner_opts.get('expr_form', _DEFAULT_EXPR_FORM), 'ignore_interfac...
Return the mine function from all the targeted minions. Just a small helper to avoid redundant pieces of code.
def _get_mine(fun): ''' Return the mine function from all the targeted minions. Just a small helper to avoid redundant pieces of code. ''' if fun in _CACHE and _CACHE[fun]: return _CACHE[fun] net_runner_opts = _get_net_runner_opts() _CACHE[fun] = __salt__['mine.get'](net_runner_opts....
Display or return the rows.
def _display_runner(rows, labels, title, display=_DEFAULT_DISPLAY): ''' Display or return the rows. ''' if display: net_runner_opts = _get_net_runner_opts() if net_runner_opts.get('outputter') == 'table': ret = salt.output.out_format({'rows': rows, 'labels': labels}, ...
Helper to search the interfaces IPs using the MAC address.
def _find_interfaces_ip(mac): ''' Helper to search the interfaces IPs using the MAC address. ''' try: mac = napalm_helpers.convert(napalm_helpers.mac, mac) except AddrFormatError: return ('', '', []) all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.i...
Helper to get the interfaces hardware address using the IP Address.
def _find_interfaces_mac(ip): # pylint: disable=invalid-name ''' Helper to get the interfaces hardware address using the IP Address. ''' all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.ipaddrs') for device, device_ipaddrs in six.iteritems(all_ipaddrs): if not ...
Search for interfaces details in the following mine functions: - net.interfaces - net.ipaddrs Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return interfaces that contain a cert...
def interfaces(device=None, interface=None, title=None, pattern=None, ipnet=None, best=True, display=_DEFAULT_DISPLAY): ''' Search for interfaces details in the following mine functions: - net.interfaces - net.ipa...
Search for entries in the ARP tables using the following mine functions: - net.arp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. mac Search using a specific MAC Address. ip Sea...
def findarp(device=None, interface=None, mac=None, ip=None, display=_DEFAULT_DISPLAY): # pylint: disable=invalid-name ''' Search for entries in the ARP tables using the following mine functions: - net.arp Optional arguments: device Return i...
Search in the MAC Address tables, using the following mine functions: - net.mac Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. mac Search using a specific MAC Address. vlan Sear...
def findmac(device=None, mac=None, interface=None, vlan=None, display=_DEFAULT_DISPLAY): ''' Search in the MAC Address tables, using the following mine functions: - net.mac Optional arguments: device Return interface data from a certain device only. interface Return data sele...
Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return LLDP neighbors that have contain this pattern in on...
def lldp(device=None, interface=None, title=None, pattern=None, chassis=None, display=_DEFAULT_DISPLAY): ''' Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a ce...
Search in all possible entities (Interfaces, MAC tables, ARP tables, LLDP neighbors), using the following mine functions: - net.mac - net.arp - net.lldp - net.ipaddrs - net.interfaces This function has the advantage that it knows where to look, but the output might become quite long as...
def find(addr, best=True, display=_DEFAULT_DISPLAY): ''' Search in all possible entities (Interfaces, MAC tables, ARP tables, LLDP neighbors), using the following mine functions: - net.mac - net.arp - net.lldp - net.ipaddrs - net.interfaces This function has the advantage that it k...
Recursive generator providing the infrastructure for augtools print behavior. This function is based on test_augeas.py from Harald Hoyer <harald@redhat.com> in the python-augeas repository
def _recurmatch(path, aug): ''' Recursive generator providing the infrastructure for augtools print behavior. This function is based on test_augeas.py from Harald Hoyer <harald@redhat.com> in the python-augeas repository ''' if path: clean_path = path.rstrip('/*') yield...
Return a copy of the string after the specified prefix was removed from the beginning of the string
def _lstrip_word(word, prefix): ''' Return a copy of the string after the specified prefix was removed from the beginning of the string ''' if six.text_type(word).startswith(prefix): return six.text_type(word)[len(prefix):] return word
Checks the validity of the load_path, returns a sanitized version with invalid paths removed.
def _check_load_paths(load_path): ''' Checks the validity of the load_path, returns a sanitized version with invalid paths removed. ''' if load_path is None or not isinstance(load_path, six.string_types): return None _paths = [] for _path in load_path.split(':'): if os.path...
Execute Augeas commands .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' augeas.execute /files/etc/redis/redis.conf \\ commands='["set bind 0.0.0.0", "set maxmemory 1G"]' context The Augeas context lens The Augeas lens to use commands ...
def execute(context=None, lens=None, commands=(), load_path=None): ''' Execute Augeas commands .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' augeas.execute /files/etc/redis/redis.conf \\ commands='["set bind 0.0.0.0", "set maxmemory 1G"]' context ...
Get a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.get /files/etc/hosts/1/ ipaddr path The path to get the value of value The optional value to get .. versionadded:: 2016.3.0 load_path A colon-spearated list of director...
def get(path, value='', load_path=None): ''' Get a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.get /files/etc/hosts/1/ ipaddr path The path to get the value of value The optional value to get .. versionadded:: 2016.3.0 ...
Set a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/1/canonical localhost This will set the first entry in /etc/hosts to localhost CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/01/ipad...
def setvalue(*args): ''' Set a value for a specific augeas path CLI Example: .. code-block:: bash salt '*' augeas.setvalue /files/etc/hosts/1/canonical localhost This will set the first entry in /etc/hosts to localhost CLI Example: .. code-block:: bash salt '*' augeas....
Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.match /files/etc/services/service-name ssh path The path to match value The value to match on .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that m...
def match(path, value='', load_path=None): ''' Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.match /files/etc/services/service-name ssh path The path to match value The value to match on .. versionadded:: 2016.3.0 load_pa...
Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.remove \\ /files/etc/sysctl.conf/net.ipv4.conf.all.log_martians path The path to remove .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules shou...
def remove(path, load_path=None): ''' Get matches for path expression CLI Example: .. code-block:: bash salt '*' augeas.remove \\ /files/etc/sysctl.conf/net.ipv4.conf.all.log_martians path The path to remove .. versionadded:: 2016.3.0 load_path A colon-s...
List the direct children of a node CLI Example: .. code-block:: bash salt '*' augeas.ls /files/etc/passwd path The path to list .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched in. This is in addition to ...
def ls(path, load_path=None): # pylint: disable=C0103 ''' List the direct children of a node CLI Example: .. code-block:: bash salt '*' augeas.ls /files/etc/passwd path The path to list .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories ...
Returns recursively the complete tree of a node CLI Example: .. code-block:: bash salt '*' augeas.tree /files/etc/ path The base of the recursive listing .. versionadded:: 2016.3.0 load_path A colon-spearated list of directories that modules should be searched i...
def tree(path, load_path=None): ''' Returns recursively the complete tree of a node CLI Example: .. code-block:: bash salt '*' augeas.tree /files/etc/ path The base of the recursive listing .. versionadded:: 2016.3.0 load_path A colon-spearated list of directori...
Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed
def list_installed(): ''' Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed ''' pkg_re = re.compile(r'^{0}-[\d.-]+-{1}$'.format( _package_prefix(), _kernel_type())) pkgs = __salt__['pkg.list_pkgs'](versions_as_list=...
Upgrade the kernel and optionally reboot the system. reboot : False Request a reboot if a new kernel is available. at_time : immediate Schedule the reboot at some point in the future. This argument is ignored if ``reboot=False``. See :py:func:`~salt.modules.system.reboot` for m...
def upgrade(reboot=False, at_time=None): ''' Upgrade the kernel and optionally reboot the system. reboot : False Request a reboot if a new kernel is available. at_time : immediate Schedule the reboot at some point in the future. This argument is ignored if ``reboot=False``. See...
Remove a specific version of the kernel. release The release number of an installed kernel. This must be the entire release number as returned by :py:func:`~salt.modules.kernelpkg_linux_apt.list_installed`, not the package name. CLI Example: .. code-block:: bash salt '*' ...
def remove(release): ''' Remove a specific version of the kernel. release The release number of an installed kernel. This must be the entire release number as returned by :py:func:`~salt.modules.kernelpkg_linux_apt.list_installed`, not the package name. CLI Example: .. cod...
Remove all unused kernel packages from the system. keep_latest : True In the event that the active kernel is not the latest one installed, setting this to True will retain the latest kernel package, in addition to the active one. If False, all kernel packages other than the active one will ...
def cleanup(keep_latest=True): ''' Remove all unused kernel packages from the system. keep_latest : True In the event that the active kernel is not the latest one installed, setting this to True will retain the latest kernel package, in addition to the active one. If False, all kernel ...
Compare function for package version sorting
def _cmp_version(item1, item2): ''' Compare function for package version sorting ''' vers1 = _LooseVersion(item1) vers2 = _LooseVersion(item2) if vers1 < vers2: return -1 if vers1 > vers2: return 1 return 0
Ensure that the key exists in redis with the value specified name Redis key to manage value Data to persist in key expire Sets time to live for key in seconds expireat Sets expiration time for key via UNIX timestamp, overrides `expire`
def string(name, value, expire=None, expireat=None, **connection_args): ''' Ensure that the key exists in redis with the value specified name Redis key to manage value Data to persist in key expire Sets time to live for key in seconds expireat Sets expiration ...
Ensure key absent from redis name Key to ensure absent from redis keys list of keys to ensure absent, name will be ignored if this is used
def absent(name, keys=None, **connection_args): ''' Ensure key absent from redis name Key to ensure absent from redis keys list of keys to ensure absent, name will be ignored if this is used ''' ret = {'name': name, 'changes': {}, 'result': True, ...
Set this redis instance as a slave. .. versionadded: 2016.3.0 name Master to make this a slave of sentinel_host Ip of the sentinel to check for the master sentinel_port Port of the sentinel to check for the master
def slaveof(name, sentinel_host=None, sentinel_port=None, sentinel_password=None, **connection_args): ''' Set this redis instance as a slave. .. versionadded: 2016.3.0 name Master to make this a slave of sentinel_host Ip of the sentinel to check for the master sentinel_port ...
This module can also be run directly for testing Args: detail|list : Provide ``detail`` or version ``list``. system|system+user: System installed and System and User installs.
def __main(): '''This module can also be run directly for testing Args: detail|list : Provide ``detail`` or version ``list``. system|system+user: System installed and System and User installs. ''' if len(sys.argv) < 3: sys.stderr.write('usage: {0} <detail|list> <syste...
Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided.
def __squid_to_guid(self, squid): ''' Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided. ...
Test for ``1`` as a number or a string and return ``True`` if it is. Args: value: string or number or None. Returns: bool: ``True`` if 1 otherwise ``False``.
def __one_equals_true(value): ''' Test for ``1`` as a number or a string and return ``True`` if it is. Args: value: string or number or None. Returns: bool: ``True`` if 1 otherwise ``False``. ''' if isinstance(value, six.integer_types) and value ...
Calls RegQueryValueEx If PY2 ensure unicode string and expand REG_EXPAND_SZ before returning Remember to catch not found exceptions when calling. Args: handle (object): open registry handle. value_name (str): Name of the value you wished returned Returns: ...
def __reg_query_value(handle, value_name): ''' Calls RegQueryValueEx If PY2 ensure unicode string and expand REG_EXPAND_SZ before returning Remember to catch not found exceptions when calling. Args: handle (object): open registry handle. value_name (str)...
Return the install time, or provide an estimate of install time. Installers or even self upgrading software must/should update the date held within InstallDate field when they change versions. Some installers do not set ``InstallDate`` at all so we use the last modified time on the regi...
def install_time(self): ''' Return the install time, or provide an estimate of install time. Installers or even self upgrading software must/should update the date held within InstallDate field when they change versions. Some installers do not set ``InstallDate`` at all so we us...
For the uninstall section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match None is return. wanted_type support values are ``str`` ``i...
def get_install_value(self, value_name, wanted_type=None): ''' For the uninstall section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match ...
For the product section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match None is return. wanted_type support values are ``str`` ``int...
def get_product_value(self, value_name, wanted_type=None): ''' For the product section of the registry return the name value. Args: value_name (str): Registry value name. wanted_type (str): The type of value wanted if the type does not match ...
For installers which follow the Microsoft Installer standard, returns the ``Upgrade code``. Returns: value (str): ``Upgrade code`` GUID for installed software.
def upgrade_code(self): ''' For installers which follow the Microsoft Installer standard, returns the ``Upgrade code``. Returns: value (str): ``Upgrade code`` GUID for installed software. ''' if not self.__squid: # Must have a valid squid for an u...
For installers which follow the Microsoft Installer standard, returns a list of patches applied. Returns: value (list): Long name of the patch.
def list_patches(self): ''' For installers which follow the Microsoft Installer standard, returns a list of patches applied. Returns: value (list): Long name of the patch. ''' if not self.__squid: # Must have a valid squid for an upgrade code to e...
Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found
def version_binary(self): ''' Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found ''' # Under MSI 'Version' is a 'REG_DWORD' which then sets other registry # values like Displ...
Returns information on a package. Args: pkg_id (str): Package Id of the software/component. Returns: list: List of version numbers installed.
def pkg_version_list(self, pkg_id): ''' Returns information on a package. Args: pkg_id (str): Package Id of the software/component. Returns: list: List of version numbers installed. ''' pkg_data = self.__reg_software.get(pkg_id, None) if ...
Provided with a valid Windows Security Identifier (SID) and returns a Username Args: sid (str): Security Identifier (SID). Returns: str: Username in the format of username@realm or username@computer.
def __sid_to_username(sid): ''' Provided with a valid Windows Security Identifier (SID) and returns a Username Args: sid (str): Security Identifier (SID). Returns: str: Username in the format of username@realm or username@computer. ''' if sid is ...
Determine the Package ID of a software/component using the software/component ``publisher``, ``name``, whether its a software or a component, and if its 32bit or 64bit archiecture. Args: publisher (str): Publisher of the software/component. name (str): Name of the softwa...
def __software_to_pkg_id(self, publisher, name, is_component, is_32bit): ''' Determine the Package ID of a software/component using the software/component ``publisher``, ``name``, whether its a software or a component, and if its 32bit or 64bit archiecture. Args: pub...
This returns the version and where the version string came from, based on instructions under ``version_capture``, if ``version_capture`` is missing, it defaults to value of display-version. Args: pkg_id (str): Publisher of the software/component. version_binary (str): Na...
def __version_capture_slp(self, pkg_id, version_binary, version_display, display_name): ''' This returns the version and where the version string came from, based on instructions under ``version_capture``, if ``version_capture`` is missing, it defaults to value of display-version. ...
Update data with the next software found
def __collect_software_info(self, sid, key_software, use_32bit): ''' Update data with the next software found ''' reg_soft_info = RegSoftwareInfo(key_software, sid, use_32bit) # Check if the registry entry is a valid. # a) Cannot manage software without at least a displ...
This searches the uninstall keys in the registry to find a match in the sub keys, it will return a dict with the display name as the key and the version as the value .. sectionauthor:: Damon Atkins <https://github.com/damon-atkins> .. versionadded:: Carbon
def __get_software_details(self, user_pkgs): ''' This searches the uninstall keys in the registry to find a match in the sub keys, it will return a dict with the display name as the key and the version as the value .. sectionauthor:: Damon Atkins <https://github.com/damon-atkins>...
Force params to be strings unless they should remain a different type
def enforce_types(key, val): ''' Force params to be strings unless they should remain a different type ''' non_string_params = { 'ssl_verify': bool, 'insecure_auth': bool, 'disable_saltenv_mapping': bool, 'env_whitelist': 'stringlist', 'env_blacklist': 'stringlist...
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): ''' Return the names of remote refs (stripped of the remote name) and tags which are map to the branches and tags. ''' def _check_ref(env_set, rname): ''' Add the appropriate saltenv(s) to the set ''' ...
Programmatically determine config value based on the desired saltenv
def add_conf_overlay(cls, name): ''' Programmatically determine config value based on the desired saltenv ''' def _getconf(self, tgt_env='base'): strip_sep = lambda x: x.rstrip(os.sep) \ if name in ('root', 'mountpoint') \ else x if...
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): ''' 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. ''' # No need to pass an environment to self.root() here since per-saltenv #...
Remove stale refs so that they are no longer seen as fileserver envs
def clean_stale_refs(self): ''' Remove stale refs so that they are no longer seen as fileserver envs ''' cleaned = [] cmd_str = 'git remote prune origin' # Attempt to force all output to plain ascii english, which is what some parsing code # may expect. #...
Clear update.lk
def clear_lock(self, lock_type='update'): ''' Clear update.lk ''' 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)) ...
For the config options which need to be maintained in the git config, ensure that the git config file is configured as desired.
def enforce_git_config(self): ''' For the config options which need to be maintained in the git config, ensure that the git config file is configured as desired. ''' git_config = os.path.join(self.gitdir, 'config') conf = salt.utils.configparser.GitConfigParser() ...
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): ''' 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. ''' try: with self.gen_lock(lock_ty...
Place a lock file if (and only if) it does not already exist.
def _lock(self, lock_type='update', failhard=False): ''' Place a lock file if (and only if) it does not already exist. ''' try: fh_ = os.open(self._get_lock_file(lock_type), os.O_CREAT | os.O_EXCL | os.O_WRONLY) with os.fdopen(fh_, 'wb'):...
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): ''' 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 ...
Set and automatically clear a lock
def gen_lock(self, lock_type='update', timeout=0, poll_interval=0.5): ''' Set and automatically clear a lock ''' if not isinstance(lock_type, six.string_types): raise GitLockError( errno.EINVAL, 'Invalid lock_type \'{0}\''.format(lock_type) ...
Check if an environment is exposed by comparing it against a whitelist and blacklist.
def env_is_exposed(self, tgt_env): ''' Check if an environment is exposed by comparing it against a whitelist and blacklist. ''' return salt.utils.stringutils.check_whitelist_blacklist( tgt_env, whitelist=self.saltenv_whitelist, blacklist=self....
Resolve dynamically-set branch
def get_checkout_target(self): ''' Resolve dynamically-set branch ''' if self.role == 'git_pillar' and self.branch == '__env__': try: return self.all_saltenvs except AttributeError: # all_saltenvs not configured for this remote ...
Return a tree object for the specified environment
def get_tree(self, tgt_env): ''' Return a tree object for the specified environment ''' 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: ...
Examine self.id and assign self.url (and self.branch, for git_pillar)
def get_url(self): ''' Examine self.id and assign self.url (and self.branch, for git_pillar) ''' if self.role in ('git_pillar', 'winrepo'): # With winrepo and git_pillar, the remote is specified in the # format '<branch> <url>', so that we can get a unique identif...
Return the expected result of an os.walk on the linkdir, based on the mountpoint value.
def linkdir_walk(self): ''' Return the expected result of an os.walk on the linkdir, based on the mountpoint value. ''' try: # Use cached linkdir_walk if we've already run this return self._linkdir_walk except AttributeError: self._link...
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): ''' 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. ''' tgt_ref = self...
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): ''' 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. ''' new = False if not os.listdir(self.cachedir): # Repo cac...
Get list of directories for the target environment using GitPython
def dir_list(self, tgt_env): ''' Get list of directories for the target environment using GitPython ''' ret = set() tree = self.get_tree(tgt_env) if not tree: return ret if self.root(tgt_env): try: tree = tree / self.root(tg...
Check the refs and return a list of the ones which can be used as salt environments.
def envs(self): ''' Check the refs and return a list of the ones which can be used as salt environments. ''' 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): ''' Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. ''' origin = self.repo.remotes[0] try: fetch_results = origin.fetch() except AssertionError: fetch_res...
Get file list for the target environment using GitPython
def file_list(self, tgt_env): ''' Get file list for the target environment using GitPython ''' files = set() symlinks = {} tree = self.get_tree(tgt_env) if not tree: # Not found, return empty objects return files, symlinks if self.r...
Find the specified file in the specified environment
def find_file(self, path, tgt_env): ''' Find the specified file in the specified environment ''' tree = self.get_tree(tgt_env) if not tree: # Branch/tag/SHA not found in repo return None, None, None blob = None depth = 0 while True:...
Return a git.Tree object matching a head ref fetched into refs/remotes/origin/
def get_tree_from_branch(self, ref): ''' Return a git.Tree object matching a head ref fetched into refs/remotes/origin/ ''' try: return git.RemoteReference( self.repo, 'refs/remotes/origin/{0}'.format(ref)).commit.tree except Va...
Return a git.Tree object matching a tag ref fetched into refs/tags/
def get_tree_from_tag(self, ref): ''' Return a git.Tree object matching a tag ref fetched into refs/tags/ ''' try: return git.TagReference( self.repo, 'refs/tags/{0}'.format(ref)).commit.tree except ValueError: return None
Return a git.Tree object matching a SHA
def get_tree_from_sha(self, ref): ''' Return a git.Tree object matching a SHA ''' try: return self.repo.rev_parse(ref).tree except (gitdb.exc.ODBError, AttributeError): return None
Using the blob object, write the file to the destination path
def write_file(self, blob, dest): ''' Using the blob object, write the file to the destination path ''' with salt.utils.files.fopen(dest, 'wb+') as fp_: blob.stream_data(fp_)
Checkout the configured branch/tag
def checkout(self): ''' Checkout the configured branch/tag ''' tgt_ref = self.get_checkout_target() local_ref = 'refs/heads/' + tgt_ref remote_ref = 'refs/remotes/origin/' + tgt_ref tag_ref = 'refs/tags/' + tgt_ref try: local_head = self.repo....
Clean stale local refs so they don't appear as fileserver environments
def clean_stale_refs(self, local_refs=None): # pylint: disable=arguments-differ ''' Clean stale local refs so they don't appear as fileserver environments ''' try: if pygit2.GIT_FETCH_PRUNE: # Don't need to clean anything, pygit2 can do it by itself ...
Initialize/attach to a remote using pygit2. 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): ''' Initialize/attach to a remote using pygit2. Return a boolean which will let the calling function know whether or not a new repo was initialized by this function. ''' # https://github.com/libgit2/pygit2/issues/339 # https://github.com/lib...
Get a list of directories for the target environment using pygit2
def dir_list(self, tgt_env): ''' Get a list of directories for the target environment using pygit2 ''' def _traverse(tree, blobs, prefix): ''' Traverse through a pygit2 Tree object recursively, accumulating all the empty directories within it in the "b...
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): ''' Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. ''' origin = self.repo.remotes[0] refs_pre = self.repo.listall_references() fetch_kwargs = {} # pygit2 radically chang...
Get file list for the target environment using pygit2
def file_list(self, tgt_env): ''' Get file list for the target environment using pygit2 ''' def _traverse(tree, blobs, prefix): ''' Traverse through a pygit2 Tree object recursively, accumulating all the file paths and symlink info in the "blobs" dict ...
Find the specified file in the specified environment
def find_file(self, path, tgt_env): ''' Find the specified file in the specified environment ''' tree = self.get_tree(tgt_env) if not tree: # Branch/tag/SHA not found in repo return None, None, None blob = None mode = None depth = 0...
Return a pygit2.Tree object matching a head ref fetched into refs/remotes/origin/
def get_tree_from_branch(self, ref): ''' Return a pygit2.Tree object matching a head ref fetched into refs/remotes/origin/ ''' try: return self.peel(self.repo.lookup_reference( 'refs/remotes/origin/{0}'.format(ref))).tree except KeyError: ...
Return a pygit2.Tree object matching a SHA
def get_tree_from_sha(self, ref): ''' Return a pygit2.Tree object matching a SHA ''' try: return self.repo.revparse_single(ref).tree except (KeyError, TypeError, ValueError, AttributeError): return None
Assign attributes for pygit2 callbacks
def setup_callbacks(self): ''' Assign attributes for pygit2 callbacks ''' if PYGIT2_VERSION >= _LooseVersion('0.23.2'): self.remotecallbacks = pygit2.RemoteCallbacks( credentials=self.credentials) if not self.ssl_verify: # Override ...
Check the username and password/keypair info for validity. If valid, set a 'credentials' attribute consisting of the appropriate Pygit2 credentials object. Return False if a required auth param is not present. Return True if the required auth parameters are present (or auth is not config...
def verify_auth(self): ''' Check the username and password/keypair info for validity. If valid, set a 'credentials' attribute consisting of the appropriate Pygit2 credentials object. Return False if a required auth param is not present. Return True if the required auth parameters...
Using the blob object, write the file to the destination path
def write_file(self, blob, dest): ''' Using the blob object, write the file to the destination path ''' with salt.utils.files.fopen(dest, 'wb+') as fp_: fp_.write(blob.data)
Initialize remotes
def init_remotes(self, remotes, per_remote_overrides=(), per_remote_only=PER_REMOTE_ONLY, global_only=GLOBAL_ONLY): ''' Initialize remotes ''' # The global versions of the auth params (gitfs_user, # gitfs_password, etc.) default to empty ...
Remove cache directories for remotes no longer configured
def clear_old_remotes(self): ''' Remove cache directories for remotes no longer configured ''' try: cachedir_ls = os.listdir(self.cache_root) except OSError: cachedir_ls = [] # Remove actively-used remotes from list for repo in self.remotes...
Completely clear cache
def clear_cache(self): ''' Completely clear cache ''' errors = [] for rdir in (self.cache_root, self.file_list_cachedir): if os.path.exists(rdir): try: shutil.rmtree(rdir) except OSError as exc: e...
Clear update.lk for all remotes
def clear_lock(self, remote=None, lock_type='update'): ''' Clear update.lk for all remotes ''' cleared = [] errors = [] for repo in self.remotes: if remote: # Specific remote URL/pattern was passed, ensure that the URL # matches...
Fetch all remotes and return a boolean to let the calling function know whether or not any remotes were updated in the process of fetching
def fetch_remotes(self, remotes=None): ''' Fetch all remotes and return a boolean to let the calling function know whether or not any remotes were updated in the process of fetching ''' if remotes is None: remotes = [] elif not isinstance(remotes, list): ...
Place an update.lk
def lock(self, remote=None): ''' Place an update.lk ''' locked = [] errors = [] for repo in self.remotes: if remote: # Specific remote URL/pattern was passed, ensure that the URL # matches or else skip this one t...
.. versionchanged:: 2018.3.0 The remotes argument was added. This being a list of remote URLs, it will only update matching remotes. This actually matches on repo.id Execute a git fetch on all of the repos and perform maintenance on the fileserver cache.
def update(self, remotes=None): ''' .. versionchanged:: 2018.3.0 The remotes argument was added. This being a list of remote URLs, it will only update matching remotes. This actually matches on repo.id Execute a git fetch on all of the repos and perform maint...
Returns a dictionary mapping remote IDs to their intervals, designed to be used for variable update intervals in salt.master.FileserverUpdate. A remote's ID is defined here as a tuple of the GitPython/Pygit2 object's "id" and "name" attributes, with None being assumed as the "name" valu...
def update_intervals(self): ''' Returns a dictionary mapping remote IDs to their intervals, designed to be used for variable update intervals in salt.master.FileserverUpdate. A remote's ID is defined here as a tuple of the GitPython/Pygit2 object's "id" and "name" attributes, wi...
Determine which provider to use
def verify_provider(self): ''' Determine which provider to use ''' if 'verified_{0}_provider'.format(self.role) in self.opts: self.provider = self.opts['verified_{0}_provider'.format(self.role)] else: desired_provider = self.opts.get('{0}_provider'.format(...
Check if GitPython is available and at a compatible version (>= 0.3.0)
def verify_gitpython(self, quiet=False): ''' Check if GitPython is available and at a compatible version (>= 0.3.0) ''' def _recommend(): if PYGIT2_VERSION and 'pygit2' in self.git_providers: log.error(_RECOMMEND_PYGIT2, self.role, self.role) if not G...
Check if pygit2/libgit2 are available and at a compatible version. Pygit2 must be at least 0.20.3 and libgit2 must be at least 0.20.0.
def verify_pygit2(self, quiet=False): ''' Check if pygit2/libgit2 are available and at a compatible version. Pygit2 must be at least 0.20.3 and libgit2 must be at least 0.20.0. ''' def _recommend(): if GITPYTHON_VERSION and 'gitpython' in self.git_providers: ...
Write the remote_map.txt
def write_remote_map(self): ''' Write the remote_map.txt ''' remote_map = salt.utils.path.join(self.cache_root, 'remote_map.txt') try: with salt.utils.files.fopen(remote_map, 'w+') as fp_: timestamp = \ datetime.now().strftime('%d %...
Common code for git_pillar/winrepo to handle locking and checking out of a repo.
def do_checkout(self, repo): ''' Common code for git_pillar/winrepo to handle locking and checking out of a repo. ''' time_start = time.time() while time.time() - time_start <= 5: try: return repo.checkout() except GitLockError as e...
Return a list of refs that can be used as environments
def envs(self, ignore_cache=False): ''' Return a list of refs that can be used as environments ''' if not ignore_cache: cache_match = salt.fileserver.check_env_cache( self.opts, self.env_cache ) if cache_match is not Non...
Find the first file to match the path and ref, read the file out of git and send the path to the newly cached file
def find_file(self, path, tgt_env='base', **kwargs): # pylint: disable=W0613 ''' Find the first file to match the path and ref, read the file out of git and send the path to the newly cached file ''' fnd = {'path': '', 'rel': ''} if os.path.isabs(path) or ...
Return a file hash, the hash type is set in the master config file
def file_hash(self, load, fnd): ''' Return a file hash, the hash type is set in the master config file ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') if not all(x in load for x in ('path', 'saltenv')): return ''...