repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/modules/service.py
status
python
def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to PID or empty string is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: string: PID if running, empty otherwise dict: Maps service name to PID if running, empty string otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return __salt__['status.pid'](sig) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: results[service] = __salt__['status.pid'](service) if contains_globbing: return results return results[name]
Return the status for a service. If the name contains globbing, a dict mapping service name to PID or empty string is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: string: PID if running, empty otherwise dict: Maps service name to PID if running, empty string otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/service.py#L125-L161
[ "def get_all():\n '''\n Return a list of all available services\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n '''\n if not os.path.isdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')):\n return []\n return sorted(os.listdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')))\n" ]
# -*- coding: utf-8 -*- ''' If Salt's OS detection does not identify a different virtual service module, the minion will fall back to using this basic module, which simply wraps sysvinit scripts. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import fnmatch import re __func_alias__ = { 'reload_': 'reload' } _GRAINMAP = { 'Arch': '/etc/rc.d', 'Arch ARM': '/etc/rc.d' } def __virtual__(): ''' Only work on systems which exclusively use sysvinit ''' # Disable on these platforms, specific service modules exist: disable = set(( 'RedHat', 'CentOS', 'Amazon', 'ScientificLinux', 'CloudLinux', 'Fedora', 'Gentoo', 'Ubuntu', 'Debian', 'Devuan', 'ALT', 'OEL', 'Linaro', 'elementary OS', 'McAfee OS Server', 'Raspbian', 'SUSE', )) if __grains__.get('os') in disable: return (False, 'Your OS is on the disabled list') # Disable on all non-Linux OSes as well if __grains__['kernel'] != 'Linux': return (False, 'Non Linux OSes are not supported') init_grain = __grains__.get('init') if init_grain not in (None, 'sysvinit', 'unknown'): return (False, 'Minion is running {0}'.format(init_grain)) elif __utils__['systemd.booted'](__context__): # Should have been caught by init grain check, but check just in case return (False, 'Minion is running systemd') return 'service' def run(name, action): ''' Run the specified service with an action. .. versionadded:: 2015.8.1 name Service name. action Action name (like start, stop, reload, restart). CLI Example: .. code-block:: bash salt '*' service.run apache2 reload salt '*' service.run postgresql initdb ''' cmd = os.path.join( _GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name ) + ' ' + action return not __salt__['cmd.retcode'](cmd, python_shell=False) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' return run(name, 'start') def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' return run(name, 'stop') def restart(name): ''' Restart the specified service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' return run(name, 'restart') def reload_(name): ''' Refreshes config files by calling service reload. Does not perform a full restart. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' return run(name, 'reload') def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' return name in get_all() def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return name not in get_all() def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' service.get_all ''' if not os.path.isdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')): return [] return sorted(os.listdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')))
saltstack/salt
salt/modules/service.py
get_all
python
def get_all(): ''' Return a list of all available services CLI Example: .. code-block:: bash salt '*' service.get_all ''' if not os.path.isdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')): return [] return sorted(os.listdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')))
Return a list of all available services CLI Example: .. code-block:: bash salt '*' service.get_all
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/service.py#L207-L219
null
# -*- coding: utf-8 -*- ''' If Salt's OS detection does not identify a different virtual service module, the minion will fall back to using this basic module, which simply wraps sysvinit scripts. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import fnmatch import re __func_alias__ = { 'reload_': 'reload' } _GRAINMAP = { 'Arch': '/etc/rc.d', 'Arch ARM': '/etc/rc.d' } def __virtual__(): ''' Only work on systems which exclusively use sysvinit ''' # Disable on these platforms, specific service modules exist: disable = set(( 'RedHat', 'CentOS', 'Amazon', 'ScientificLinux', 'CloudLinux', 'Fedora', 'Gentoo', 'Ubuntu', 'Debian', 'Devuan', 'ALT', 'OEL', 'Linaro', 'elementary OS', 'McAfee OS Server', 'Raspbian', 'SUSE', )) if __grains__.get('os') in disable: return (False, 'Your OS is on the disabled list') # Disable on all non-Linux OSes as well if __grains__['kernel'] != 'Linux': return (False, 'Non Linux OSes are not supported') init_grain = __grains__.get('init') if init_grain not in (None, 'sysvinit', 'unknown'): return (False, 'Minion is running {0}'.format(init_grain)) elif __utils__['systemd.booted'](__context__): # Should have been caught by init grain check, but check just in case return (False, 'Minion is running systemd') return 'service' def run(name, action): ''' Run the specified service with an action. .. versionadded:: 2015.8.1 name Service name. action Action name (like start, stop, reload, restart). CLI Example: .. code-block:: bash salt '*' service.run apache2 reload salt '*' service.run postgresql initdb ''' cmd = os.path.join( _GRAINMAP.get(__grains__.get('os'), '/etc/init.d'), name ) + ' ' + action return not __salt__['cmd.retcode'](cmd, python_shell=False) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' return run(name, 'start') def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' return run(name, 'stop') def restart(name): ''' Restart the specified service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' return run(name, 'restart') def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to PID or empty string is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: string: PID if running, empty otherwise dict: Maps service name to PID if running, empty string otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return __salt__['status.pid'](sig) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: results[service] = __salt__['status.pid'](service) if contains_globbing: return results return results[name] def reload_(name): ''' Refreshes config files by calling service reload. Does not perform a full restart. CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' return run(name, 'reload') def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' return name in get_all() def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return name not in get_all()
saltstack/salt
salt/pillar/neutron.py
_auth
python
def _auth(profile=None): ''' Set up neutron credentials ''' credentials = __salt__['config.option'](profile) kwargs = { 'username': credentials['keystone.user'], 'password': credentials['keystone.password'], 'tenant_name': credentials['keystone.tenant'], 'auth_url': credentials['keystone.auth_url'], 'region_name': credentials.get('keystone.region_name', None), 'service_type': credentials['keystone.service_type'], } return suoneu.SaltNeutron(**kwargs)
Set up neutron credentials
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/neutron.py#L68-L82
null
# -*- coding: utf-8 -*- ''' Use Openstack Neutron data as a Pillar source. Will list all networks listed inside of Neutron, to all minions. .. versionadded:: 2015.5.1 :depends: - python-neutronclient A keystone profile must be used for the pillar to work (no generic keystone configuration here). For example: .. code-block:: yaml my openstack_config: keystone.user: 'admin' keystone.password: 'password' keystone.tenant: 'admin' keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' keystone.region_name: 'RegionOne' keystone.service_type: 'network' After the profile is created, configure the external pillar system to use it. .. code-block:: yaml ext_pillar: - neutron: my_openstack_config Using these configuration profiles, multiple neutron sources may also be used: .. code-block:: yaml ext_pillar: - neutron: my_openstack_config - neutron: my_other_openstack_config By default, these networks will be returned as a pillar item called ``networks``. In order to have them returned under a different name, add the name after the Keystone profile name: ext_pillar: - neutron: my_openstack_config neutron_networks ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs try: import salt.utils.openstack.neutron as suoneu HAS_NEUTRON = True except NameError as exc: HAS_NEUTRON = False # Set up logging log = logging.getLogger(__name__) def __virtual__(): ''' Only return if python-neutronclient is installed ''' return HAS_NEUTRON def ext_pillar(minion_id, pillar, # pylint: disable=W0613 conf): ''' Check neutron for all data ''' comps = conf.split() profile = None if comps[0]: profile = comps[0] conn = _auth(profile) ret = {} networks = conn.list_networks() for network in networks['networks']: ret[network['name']] = network if len(comps) < 2: comps.append('networks') return {comps[1]: ret}
saltstack/salt
salt/pillar/neutron.py
ext_pillar
python
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 conf): ''' Check neutron for all data ''' comps = conf.split() profile = None if comps[0]: profile = comps[0] conn = _auth(profile) ret = {} networks = conn.list_networks() for network in networks['networks']: ret[network['name']] = network if len(comps) < 2: comps.append('networks') return {comps[1]: ret}
Check neutron for all data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/neutron.py#L85-L105
[ "def _auth(profile=None):\n '''\n Set up neutron credentials\n '''\n credentials = __salt__['config.option'](profile)\n kwargs = {\n 'username': credentials['keystone.user'],\n 'password': credentials['keystone.password'],\n 'tenant_name': credentials['keystone.tenant'],\n 'auth_url': credentials['keystone.auth_url'],\n 'region_name': credentials.get('keystone.region_name', None),\n 'service_type': credentials['keystone.service_type'],\n }\n\n return suoneu.SaltNeutron(**kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Use Openstack Neutron data as a Pillar source. Will list all networks listed inside of Neutron, to all minions. .. versionadded:: 2015.5.1 :depends: - python-neutronclient A keystone profile must be used for the pillar to work (no generic keystone configuration here). For example: .. code-block:: yaml my openstack_config: keystone.user: 'admin' keystone.password: 'password' keystone.tenant: 'admin' keystone.auth_url: 'http://127.0.0.1:5000/v2.0/' keystone.region_name: 'RegionOne' keystone.service_type: 'network' After the profile is created, configure the external pillar system to use it. .. code-block:: yaml ext_pillar: - neutron: my_openstack_config Using these configuration profiles, multiple neutron sources may also be used: .. code-block:: yaml ext_pillar: - neutron: my_openstack_config - neutron: my_other_openstack_config By default, these networks will be returned as a pillar item called ``networks``. In order to have them returned under a different name, add the name after the Keystone profile name: ext_pillar: - neutron: my_openstack_config neutron_networks ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Libs try: import salt.utils.openstack.neutron as suoneu HAS_NEUTRON = True except NameError as exc: HAS_NEUTRON = False # Set up logging log = logging.getLogger(__name__) def __virtual__(): ''' Only return if python-neutronclient is installed ''' return HAS_NEUTRON def _auth(profile=None): ''' Set up neutron credentials ''' credentials = __salt__['config.option'](profile) kwargs = { 'username': credentials['keystone.user'], 'password': credentials['keystone.password'], 'tenant_name': credentials['keystone.tenant'], 'auth_url': credentials['keystone.auth_url'], 'region_name': credentials.get('keystone.region_name', None), 'service_type': credentials['keystone.service_type'], } return suoneu.SaltNeutron(**kwargs)
saltstack/salt
salt/states/mssql_database.py
present
python
def present(name, containment='NONE', options=None, **kwargs): ''' Ensure that the named database is present with the specified options name The name of the database to manage containment Defaults to NONE options Can be a list of strings, a dictionary, or a list of dictionaries ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if __salt__['mssql.db_exists'](name, **kwargs): ret['comment'] = 'Database {0} is already present (Not going to try to set its options)'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Database {0} is set to be added'.format(name) return ret db_created = __salt__['mssql.db_create'](name, containment=containment, new_database_options=_normalize_options(options), **kwargs) if db_created is not True: # Non-empty strings are also evaluated to True, so we cannot use if not db_created: ret['result'] = False ret['comment'] += 'Database {0} failed to be created: {1}'.format(name, db_created) return ret ret['comment'] += 'Database {0} has been added'.format(name) ret['changes'][name] = 'Present' return ret
Ensure that the named database is present with the specified options name The name of the database to manage containment Defaults to NONE options Can be a list of strings, a dictionary, or a list of dictionaries
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mssql_database.py#L36-L67
[ "def _normalize_options(options):\n if type(options) in [dict, collections.OrderedDict]:\n return ['{0}={1}'.format(k, v) for k, v in options.items()]\n if type(options) is list and (not options or type(options[0]) is str):\n return options\n # Invalid options\n if type(options) is not list or type(options[0]) not in [dict, collections.OrderedDict]:\n return []\n return [o for d in options for o in _normalize_options(d)]\n" ]
# -*- coding: utf-8 -*- ''' Management of Microsoft SQLServer Databases =========================================== The mssql_database module is used to create and manage SQL Server Databases .. code-block:: yaml yolo: mssql_database.present ''' from __future__ import absolute_import, print_function, unicode_literals import collections def __virtual__(): ''' Only load if the mssql module is present ''' return 'mssql.version' in __salt__ def _normalize_options(options): if type(options) in [dict, collections.OrderedDict]: return ['{0}={1}'.format(k, v) for k, v in options.items()] if type(options) is list and (not options or type(options[0]) is str): return options # Invalid options if type(options) is not list or type(options[0]) not in [dict, collections.OrderedDict]: return [] return [o for d in options for o in _normalize_options(d)] def absent(name, **kwargs): ''' Ensure that the named database is absent name The name of the database to remove ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not __salt__['mssql.db_exists'](name): ret['comment'] = 'Database {0} is not present'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Database {0} is set to be removed'.format(name) return ret if __salt__['mssql.db_remove'](name, **kwargs): ret['comment'] = 'Database {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret # else: ret['result'] = False ret['comment'] = 'Database {0} failed to be removed'.format(name) return ret
saltstack/salt
salt/fileclient.py
get_file_client
python
def get_file_client(opts, pillar=False): ''' Read in the ``file_client`` option and return the correct type of file server ''' client = opts.get('file_client', 'remote') if pillar and client == 'local': client = 'pillar' return { 'remote': RemoteClient, 'local': FSClient, 'pillar': PillarClient, }.get(client, RemoteClient)(opts)
Read in the ``file_client`` option and return the correct type of file server
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L52-L64
null
# -*- coding: utf-8 -*- ''' Classes that manage file clients ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import contextlib import errno import logging import os import string import shutil import ftplib from tornado.httputil import parse_response_start_line, HTTPHeaders, HTTPInputError import salt.utils.atomicfile # Import salt libs from salt.exceptions import ( CommandExecutionError, MinionError ) import salt.client import salt.crypt import salt.loader import salt.payload import salt.transport.client import salt.fileserver import salt.utils.data import salt.utils.files import salt.utils.gzip_util import salt.utils.hashutils import salt.utils.http import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.versions from salt.utils.openstack.swift import SaltSwift # pylint: disable=no-name-in-module,import-error from salt.ext import six import salt.ext.six.moves.BaseHTTPServer as BaseHTTPServer from salt.ext.six.moves.urllib.error import HTTPError, URLError from salt.ext.six.moves.urllib.parse import urlparse, urlunparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) MAX_FILENAME_LENGTH = 255 def decode_dict_keys_to_str(src): ''' Convert top level keys from bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types. ''' if not six.PY3 or not isinstance(src, dict): return src output = {} for key, val in six.iteritems(src): if isinstance(key, bytes): try: key = key.decode() except UnicodeError: pass output[key] = val return output class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name ) class PillarClient(Client): ''' Used by pillar to handle fileclient requests ''' def _find_file(self, path, saltenv='base'): ''' Locate the file path ''' fnd = {'path': '', 'rel': ''} if salt.utils.url.is_escaped(path): # The path arguments are escaped path = salt.utils.url.unescape(path) for root in self.opts['pillar_roots'].get(saltenv, []): full = os.path.join(root, path) if os.path.isfile(full): fnd['path'] = full fnd['rel'] = path return fnd return fnd def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files ''' path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get('path') if not fnd_path: return '' return fnd_path def file_list(self, saltenv='base', prefix=''): ''' Return a list of files in the given environment with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] for fname in files: relpath = os.path.relpath(os.path.join(root, fname), path) ret.append(salt.utils.data.decode(relpath)) return ret def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] if not dirs and not files: ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def dir_list(self, saltenv='base', prefix=''): ''' List the dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def __get_file_path(self, path, saltenv='base'): ''' Return either a file path or the result of a remote find_file call. ''' try: path = self._check_proto(path) except MinionError as err: # Local file path if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return None else: return path return self._find_file(path, saltenv) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] except TypeError: # Local file path fnd_path = fnd hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret def hash_and_stat_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret, None try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] fnd_stat = fnd.get('stat') except TypeError: # Local file path fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: fnd_stat = None hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret, fnd_stat def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' return self.file_list(saltenv) def master_opts(self): ''' Return the master opts data ''' return self.opts def envs(self): ''' Return the available environments ''' ret = [] for saltenv in self.opts['pillar_roots']: ret.append(saltenv) return ret def master_tops(self): ''' Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environment yet. It's worth noting that originally this fn started with if 'external_nodes' not in opts: return {} So since external_nodes is gone now, we are just returning the empty dict. ''' return {} class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) class FSClient(RemoteClient): ''' A local client that uses the RemoteClient but substitutes the channel for the FSChan object ''' def __init__(self, opts): # pylint: disable=W0231 Client.__init__(self, opts) # pylint: disable=W0233 self._closing = False self.channel = salt.fileserver.FSChan(opts) self.auth = DumbAuth() # Provide backward compatibility for anyone directly using LocalClient (but no # one should be doing this). LocalClient = FSClient class DumbAuth(object): ''' The dumbauth class is used to stub out auth calls fired from the FSClient subsystem ''' def gen_token(self, clear_tok): return clear_tok
saltstack/salt
salt/fileclient.py
decode_dict_keys_to_str
python
def decode_dict_keys_to_str(src): ''' Convert top level keys from bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types. ''' if not six.PY3 or not isinstance(src, dict): return src output = {} for key, val in six.iteritems(src): if isinstance(key, bytes): try: key = key.decode() except UnicodeError: pass output[key] = val return output
Convert top level keys from bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L67-L84
null
# -*- coding: utf-8 -*- ''' Classes that manage file clients ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import contextlib import errno import logging import os import string import shutil import ftplib from tornado.httputil import parse_response_start_line, HTTPHeaders, HTTPInputError import salt.utils.atomicfile # Import salt libs from salt.exceptions import ( CommandExecutionError, MinionError ) import salt.client import salt.crypt import salt.loader import salt.payload import salt.transport.client import salt.fileserver import salt.utils.data import salt.utils.files import salt.utils.gzip_util import salt.utils.hashutils import salt.utils.http import salt.utils.path import salt.utils.platform import salt.utils.stringutils import salt.utils.templates import salt.utils.url import salt.utils.versions from salt.utils.openstack.swift import SaltSwift # pylint: disable=no-name-in-module,import-error from salt.ext import six import salt.ext.six.moves.BaseHTTPServer as BaseHTTPServer from salt.ext.six.moves.urllib.error import HTTPError, URLError from salt.ext.six.moves.urllib.parse import urlparse, urlunparse # pylint: enable=no-name-in-module,import-error log = logging.getLogger(__name__) MAX_FILENAME_LENGTH = 255 def get_file_client(opts, pillar=False): ''' Read in the ``file_client`` option and return the correct type of file server ''' client = opts.get('file_client', 'remote') if pillar and client == 'local': client = 'pillar' return { 'remote': RemoteClient, 'local': FSClient, 'pillar': PillarClient, }.get(client, RemoteClient)(opts) class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name ) class PillarClient(Client): ''' Used by pillar to handle fileclient requests ''' def _find_file(self, path, saltenv='base'): ''' Locate the file path ''' fnd = {'path': '', 'rel': ''} if salt.utils.url.is_escaped(path): # The path arguments are escaped path = salt.utils.url.unescape(path) for root in self.opts['pillar_roots'].get(saltenv, []): full = os.path.join(root, path) if os.path.isfile(full): fnd['path'] = full fnd['rel'] = path return fnd return fnd def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files ''' path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get('path') if not fnd_path: return '' return fnd_path def file_list(self, saltenv='base', prefix=''): ''' Return a list of files in the given environment with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] for fname in files: relpath = os.path.relpath(os.path.join(root, fname), path) ret.append(salt.utils.data.decode(relpath)) return ret def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] if not dirs and not files: ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def dir_list(self, saltenv='base', prefix=''): ''' List the dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def __get_file_path(self, path, saltenv='base'): ''' Return either a file path or the result of a remote find_file call. ''' try: path = self._check_proto(path) except MinionError as err: # Local file path if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return None else: return path return self._find_file(path, saltenv) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] except TypeError: # Local file path fnd_path = fnd hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret def hash_and_stat_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret, None try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] fnd_stat = fnd.get('stat') except TypeError: # Local file path fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: fnd_stat = None hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret, fnd_stat def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' return self.file_list(saltenv) def master_opts(self): ''' Return the master opts data ''' return self.opts def envs(self): ''' Return the available environments ''' ret = [] for saltenv in self.opts['pillar_roots']: ret.append(saltenv) return ret def master_tops(self): ''' Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environment yet. It's worth noting that originally this fn started with if 'external_nodes' not in opts: return {} So since external_nodes is gone now, we are just returning the empty dict. ''' return {} class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) class FSClient(RemoteClient): ''' A local client that uses the RemoteClient but substitutes the channel for the FSChan object ''' def __init__(self, opts): # pylint: disable=W0231 Client.__init__(self, opts) # pylint: disable=W0233 self._closing = False self.channel = salt.fileserver.FSChan(opts) self.auth = DumbAuth() # Provide backward compatibility for anyone directly using LocalClient (but no # one should be doing this). LocalClient = FSClient class DumbAuth(object): ''' The dumbauth class is used to stub out auth calls fired from the FSClient subsystem ''' def gen_token(self, clear_tok): return clear_tok
saltstack/salt
salt/fileclient.py
Client._check_proto
python
def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path
Make sure that this path is intended for the salt master and trim it
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L109-L116
[ "def parse(url):\n '''\n Parse a salt:// URL; return the path and a possible saltenv query.\n '''\n if not url.startswith('salt://'):\n return url, None\n\n # urlparse will split on valid filename chars such as '?' and '&'\n resource = url.split('salt://', 1)[-1]\n\n if '?env=' in resource:\n # \"env\" is not supported; Use \"saltenv\".\n path, saltenv = resource.split('?env=', 1)[0], None\n elif '?saltenv=' in resource:\n path, saltenv = resource.split('?saltenv=', 1)\n else:\n path, saltenv = resource, None\n\n if salt.utils.platform.is_windows():\n path = salt.utils.path.sanitize_win_path(path)\n\n return path, saltenv\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client._file_local_list
python
def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist
Helper util to return a list of files in a directory
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L118-L134
[ "def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client._cache_loc
python
def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest
Return the local location to cache the file, cache dirs will be made
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L137-L160
null
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.get_file
python
def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError
Copies a file from the local files or master depending on implementation
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L169-L180
null
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.cache_file
python
def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash)
Pull a file down from the file server and store it in the minion file cache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L188-L194
[ "def get_url(self, url, dest, makedirs=False, saltenv='base',\n no_cache=False, cachedir=None, source_hash=None):\n '''\n Get a single file from a URL.\n '''\n url_data = urlparse(url)\n url_scheme = url_data.scheme\n url_path = os.path.join(\n url_data.netloc, url_data.path).rstrip(os.sep)\n\n # If dest is a directory, rewrite dest with filename\n if dest is not None \\\n and (os.path.isdir(dest) or dest.endswith(('/', '\\\\'))):\n if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'):\n strpath = url.split('/')[-1]\n else:\n strpath = 'index.html'\n\n if salt.utils.platform.is_windows():\n strpath = salt.utils.path.sanitize_win_path(strpath)\n\n dest = os.path.join(dest, strpath)\n\n if url_scheme and url_scheme.lower() in string.ascii_lowercase:\n url_path = ':'.join((url_scheme, url_path))\n url_scheme = 'file'\n\n if url_scheme in ('file', ''):\n # Local filesystem\n if not os.path.isabs(url_path):\n raise CommandExecutionError(\n 'Path \\'{0}\\' is not absolute'.format(url_path)\n )\n if dest is None:\n with salt.utils.files.fopen(url_path, 'rb') as fp_:\n data = fp_.read()\n return data\n return url_path\n\n if url_scheme == 'salt':\n result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir)\n if result and dest is None:\n with salt.utils.files.fopen(result, 'rb') as fp_:\n data = fp_.read()\n return data\n return result\n\n if dest:\n destdir = os.path.dirname(dest)\n if not os.path.isdir(destdir):\n if makedirs:\n os.makedirs(destdir)\n else:\n return ''\n elif not no_cache:\n dest = self._extrn_path(url, saltenv, cachedir=cachedir)\n if source_hash is not None:\n try:\n source_hash = source_hash.split('=')[-1]\n form = salt.utils.files.HASHES_REVMAP[len(source_hash)]\n if salt.utils.hashutils.get_hash(dest, form) == source_hash:\n log.debug(\n 'Cached copy of %s (%s) matches source_hash %s, '\n 'skipping download', url, dest, source_hash\n )\n return dest\n except (AttributeError, KeyError, IOError, OSError):\n pass\n destdir = os.path.dirname(dest)\n if not os.path.isdir(destdir):\n os.makedirs(destdir)\n\n if url_data.scheme == 's3':\n try:\n def s3_opt(key, default=None):\n '''\n Get value of s3.<key> from Minion config or from Pillar\n '''\n if 's3.' + key in self.opts:\n return self.opts['s3.' + key]\n try:\n return self.opts['pillar']['s3'][key]\n except (KeyError, TypeError):\n return default\n self.utils['s3.query'](method='GET',\n bucket=url_data.netloc,\n path=url_data.path[1:],\n return_bin=False,\n local_file=dest,\n action=None,\n key=s3_opt('key'),\n keyid=s3_opt('keyid'),\n service_url=s3_opt('service_url'),\n verify_ssl=s3_opt('verify_ssl', True),\n location=s3_opt('location'),\n path_style=s3_opt('path_style', False),\n https_enable=s3_opt('https_enable', True))\n return dest\n except Exception as exc:\n raise MinionError(\n 'Could not fetch from {0}. Exception: {1}'.format(url, exc)\n )\n if url_data.scheme == 'ftp':\n try:\n ftp = ftplib.FTP()\n ftp.connect(url_data.hostname, url_data.port)\n ftp.login(url_data.username, url_data.password)\n remote_file_path = url_data.path.lstrip('/')\n with salt.utils.files.fopen(dest, 'wb') as fp_:\n ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write)\n ftp.quit()\n return dest\n except Exception as exc:\n raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc))\n\n if url_data.scheme == 'swift':\n try:\n def swift_opt(key, default):\n '''\n Get value of <key> from Minion config or from Pillar\n '''\n if key in self.opts:\n return self.opts[key]\n try:\n return self.opts['pillar'][key]\n except (KeyError, TypeError):\n return default\n\n swift_conn = SaltSwift(swift_opt('keystone.user', None),\n swift_opt('keystone.tenant', None),\n swift_opt('keystone.auth_url', None),\n swift_opt('keystone.password', None))\n\n swift_conn.get_object(url_data.netloc,\n url_data.path[1:],\n dest)\n return dest\n except Exception:\n raise MinionError('Could not fetch from {0}'.format(url))\n\n get_kwargs = {}\n if url_data.username is not None \\\n and url_data.scheme in ('http', 'https'):\n netloc = url_data.netloc\n at_sign_pos = netloc.rfind('@')\n if at_sign_pos != -1:\n netloc = netloc[at_sign_pos + 1:]\n fixed_url = urlunparse(\n (url_data.scheme, netloc, url_data.path,\n url_data.params, url_data.query, url_data.fragment))\n get_kwargs['auth'] = (url_data.username, url_data.password)\n else:\n fixed_url = url\n\n destfp = None\n try:\n # Tornado calls streaming_callback on redirect response bodies.\n # But we need streaming to support fetching large files (> RAM\n # avail). Here we are working around this by disabling recording\n # the body for redirections. The issue is fixed in Tornado 4.3.0\n # so on_header callback could be removed when we'll deprecate\n # Tornado<4.3.0. See #27093 and #30431 for details.\n\n # Use list here to make it writable inside the on_header callback.\n # Simple bool doesn't work here: on_header creates a new local\n # variable instead. This could be avoided in Py3 with 'nonlocal'\n # statement. There is no Py2 alternative for this.\n #\n # write_body[0] is used by the on_chunk callback to tell it whether\n # or not we need to write the body of the request to disk. For\n # 30x redirects we set this to False because we don't want to\n # write the contents to disk, as we will need to wait until we\n # get to the redirected URL.\n #\n # write_body[1] will contain a tornado.httputil.HTTPHeaders\n # instance that we will use to parse each header line. We\n # initialize this to False, and after we parse the status line we\n # will replace it with the HTTPHeaders instance. If/when we have\n # found the encoding used in the request, we set this value to\n # False to signify that we are done parsing.\n #\n # write_body[2] is where the encoding will be stored\n write_body = [None, False, None]\n\n def on_header(hdr):\n if write_body[1] is not False and write_body[2] is None:\n if not hdr.strip() and 'Content-Type' not in write_body[1]:\n # If write_body[0] is True, then we are not following a\n # redirect (initial response was a 200 OK). So there is\n # no need to reset write_body[0].\n if write_body[0] is not True:\n # We are following a redirect, so we need to reset\n # write_body[0] so that we properly follow it.\n write_body[0] = None\n # We don't need the HTTPHeaders object anymore\n write_body[1] = False\n return\n # Try to find out what content type encoding is used if\n # this is a text file\n write_body[1].parse_line(hdr) # pylint: disable=no-member\n if 'Content-Type' in write_body[1]:\n content_type = write_body[1].get('Content-Type') # pylint: disable=no-member\n if not content_type.startswith('text'):\n write_body[1] = write_body[2] = False\n else:\n encoding = 'utf-8'\n fields = content_type.split(';')\n for field in fields:\n if 'encoding' in field:\n encoding = field.split('encoding=')[-1]\n write_body[2] = encoding\n # We have found our encoding. Stop processing headers.\n write_body[1] = False\n\n # If write_body[0] is False, this means that this\n # header is a 30x redirect, so we need to reset\n # write_body[0] to None so that we parse the HTTP\n # status code from the redirect target. Additionally,\n # we need to reset write_body[2] so that we inspect the\n # headers for the Content-Type of the URL we're\n # following.\n if write_body[0] is write_body[1] is False:\n write_body[0] = write_body[2] = None\n\n # Check the status line of the HTTP request\n if write_body[0] is None:\n try:\n hdr = parse_response_start_line(hdr)\n except HTTPInputError:\n # Not the first line, do nothing\n return\n write_body[0] = hdr.code not in [301, 302, 303, 307]\n write_body[1] = HTTPHeaders()\n\n if no_cache:\n result = []\n\n def on_chunk(chunk):\n if write_body[0]:\n if write_body[2]:\n chunk = chunk.decode(write_body[2])\n result.append(chunk)\n else:\n dest_tmp = u\"{0}.part\".format(dest)\n # We need an open filehandle to use in the on_chunk callback,\n # that's why we're not using a with clause here.\n destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage\n\n def on_chunk(chunk):\n if write_body[0]:\n destfp.write(chunk)\n\n query = salt.utils.http.query(\n fixed_url,\n stream=True,\n streaming_callback=on_chunk,\n header_callback=on_header,\n username=url_data.username,\n password=url_data.password,\n opts=self.opts,\n **get_kwargs\n )\n if 'handle' not in query:\n raise MinionError('Error: {0} reading {1}'.format(query['error'], url))\n if no_cache:\n if write_body[2]:\n return ''.join(result)\n return b''.join(result)\n else:\n destfp.close()\n destfp = None\n salt.utils.files.rename(dest_tmp, dest)\n return dest\n except HTTPError as exc:\n raise MinionError('HTTP error {0} reading {1}: {3}'.format(\n exc.code,\n url,\n *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code]))\n except URLError as exc:\n raise MinionError('Error reading {0}: {1}'.format(url, exc.reason))\n finally:\n if destfp is not None:\n destfp.close()\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.cache_files
python
def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret
Download a list of files stored on the master and put them in the minion file cache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L196-L206
[ "def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None):\n '''\n Pull a file down from the file server and store it in the minion\n file cache\n '''\n return self.get_url(\n path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash)\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.cache_master
python
def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret
Download and cache all files on a master in a specified environment
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L208-L218
[ "def create(path, saltenv=None):\n '''\n join `path` and `saltenv` into a 'salt://' URL.\n '''\n if salt.utils.platform.is_windows():\n path = salt.utils.path.sanitize_win_path(path)\n path = salt.utils.data.decode(path)\n\n query = 'saltenv={0}'.format(saltenv) if saltenv else ''\n url = salt.utils.data.decode(urlunparse(('file', '', path, '', query, '')))\n return 'salt://{0}'.format(url[len('file:///'):])\n", "def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None):\n '''\n Pull a file down from the file server and store it in the minion\n file cache\n '''\n return self.get_url(\n path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash)\n", "def file_list(self, saltenv='base', prefix=''):\n '''\n This function must be overwritten\n '''\n return []\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.cache_dir
python
def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret
Download all of the files in a subdir of the master
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L220-L269
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n", "def _check_proto(self, path):\n '''\n Make sure that this path is intended for the salt master and trim it\n '''\n if not path.startswith('salt://'):\n raise MinionError('Unsupported path: {0}'.format(path))\n file_path, saltenv = salt.utils.url.parse(path)\n return file_path\n", "def get_cachedir(self, cachedir=None):\n if cachedir is None:\n cachedir = self.opts['cachedir']\n elif not os.path.isabs(cachedir):\n cachedir = os.path.join(self.opts['cachedir'], cachedir)\n return cachedir\n", "def file_list_emptydirs(self, saltenv='base', prefix=''):\n '''\n List the empty dirs\n '''\n raise NotImplementedError\n", "def file_list(self, saltenv='base', prefix=''):\n '''\n This function must be overwritten\n '''\n return []\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.cache_local_file
python
def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest
Cache a local file on the minion in the localfiles cache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L271-L283
null
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.file_local_list
python
def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest))
List files in the local minion files and localfiles caches
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L285-L294
[ "def _file_local_list(self, dest):\n '''\n Helper util to return a list of files in a directory\n '''\n if os.path.isdir(dest):\n destdir = dest\n else:\n destdir = os.path.dirname(dest)\n\n filelist = set()\n\n for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True):\n for name in files:\n path = os.path.join(root, name)\n filelist.add(path)\n\n return filelist\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.is_cached
python
def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return ''
Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L314-L342
[ "def parse(url):\n '''\n Parse a salt:// URL; return the path and a possible saltenv query.\n '''\n if not url.startswith('salt://'):\n return url, None\n\n # urlparse will split on valid filename chars such as '?' and '&'\n resource = url.split('salt://', 1)[-1]\n\n if '?env=' in resource:\n # \"env\" is not supported; Use \"saltenv\".\n path, saltenv = resource.split('?env=', 1)[0], None\n elif '?saltenv=' in resource:\n path, saltenv = resource.split('?saltenv=', 1)\n else:\n path, saltenv = resource, None\n\n if salt.utils.platform.is_windows():\n path = salt.utils.path.sanitize_win_path(path)\n\n return path, saltenv\n", "def escape(url):\n '''\n add escape character `|` to `url`\n '''\n if salt.utils.platform.is_windows():\n return url\n\n scheme = urlparse(url).scheme\n if not scheme:\n if url.startswith('|'):\n return url\n else:\n return '|{0}'.format(url)\n elif scheme == 'salt':\n path, saltenv = parse(url)\n if path.startswith('|'):\n return create(path, saltenv)\n else:\n return create('|{0}'.format(path), saltenv)\n else:\n return url\n", "def is_escaped(url):\n '''\n test whether `url` is escaped with `|`\n '''\n scheme = urlparse(url).scheme\n if not scheme:\n return url.startswith('|')\n elif scheme == 'salt':\n path, saltenv = parse(url)\n if salt.utils.platform.is_windows() and '|' in url:\n return path.startswith('_')\n else:\n return path.startswith('|')\n else:\n return False\n", "def _extrn_path(self, url, saltenv, cachedir=None):\n '''\n Return the extrn_filepath for a given url\n '''\n url_data = urlparse(url)\n if salt.utils.platform.is_windows():\n netloc = salt.utils.path.sanitize_win_path(url_data.netloc)\n else:\n netloc = url_data.netloc\n\n # Strip user:pass from URLs\n netloc = netloc.split('@')[-1]\n\n if cachedir is None:\n cachedir = self.opts['cachedir']\n elif not os.path.isabs(cachedir):\n cachedir = os.path.join(self.opts['cachedir'], cachedir)\n\n if url_data.query:\n file_name = '-'.join([url_data.path, url_data.query])\n else:\n file_name = url_data.path\n\n if len(file_name) > MAX_FILENAME_LENGTH:\n file_name = salt.utils.hashutils.sha256_digest(file_name)\n\n return salt.utils.path.join(\n cachedir,\n 'extrn_files',\n saltenv,\n netloc,\n file_name\n )\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.cache_dest
python
def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir)
Return the expected cache location for the specified URL and environment.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L344-L365
[ "def parse(url):\n '''\n Parse a salt:// URL; return the path and a possible saltenv query.\n '''\n if not url.startswith('salt://'):\n return url, None\n\n # urlparse will split on valid filename chars such as '?' and '&'\n resource = url.split('salt://', 1)[-1]\n\n if '?env=' in resource:\n # \"env\" is not supported; Use \"saltenv\".\n path, saltenv = resource.split('?env=', 1)[0], None\n elif '?saltenv=' in resource:\n path, saltenv = resource.split('?saltenv=', 1)\n else:\n path, saltenv = resource, None\n\n if salt.utils.platform.is_windows():\n path = salt.utils.path.sanitize_win_path(path)\n\n return path, saltenv\n", "def _extrn_path(self, url, saltenv, cachedir=None):\n '''\n Return the extrn_filepath for a given url\n '''\n url_data = urlparse(url)\n if salt.utils.platform.is_windows():\n netloc = salt.utils.path.sanitize_win_path(url_data.netloc)\n else:\n netloc = url_data.netloc\n\n # Strip user:pass from URLs\n netloc = netloc.split('@')[-1]\n\n if cachedir is None:\n cachedir = self.opts['cachedir']\n elif not os.path.isabs(cachedir):\n cachedir = os.path.join(self.opts['cachedir'], cachedir)\n\n if url_data.query:\n file_name = '-'.join([url_data.path, url_data.query])\n else:\n file_name = url_data.path\n\n if len(file_name) > MAX_FILENAME_LENGTH:\n file_name = salt.utils.hashutils.sha256_digest(file_name)\n\n return salt.utils.path.join(\n cachedir,\n 'extrn_files',\n saltenv,\n netloc,\n file_name\n )\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.list_states
python
def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states)
Return a list of all available sls modules on the master for a given environment
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L367-L382
[ "def file_list(self, saltenv='base', prefix=''):\n '''\n This function must be overwritten\n '''\n return []\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.get_state
python
def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {}
Get a state file from the master and store it in the local minion cache; return the location of the file
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L384-L397
[ "def create(path, saltenv=None):\n '''\n join `path` and `saltenv` into a 'salt://' URL.\n '''\n if salt.utils.platform.is_windows():\n path = salt.utils.path.sanitize_win_path(path)\n path = salt.utils.data.decode(path)\n\n query = 'saltenv={0}'.format(saltenv) if saltenv else ''\n url = salt.utils.data.decode(urlunparse(('file', '', path, '', query, '')))\n return 'salt://{0}'.format(url[len('file:///'):])\n", "def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None):\n '''\n Pull a file down from the file server and store it in the minion\n file cache\n '''\n return self.get_url(\n path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash)\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.get_dir
python
def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret
Get a directory recursively from the salt-master
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L399-L456
[ "def create(path, saltenv=None):\n '''\n join `path` and `saltenv` into a 'salt://' URL.\n '''\n if salt.utils.platform.is_windows():\n path = salt.utils.path.sanitize_win_path(path)\n path = salt.utils.data.decode(path)\n\n query = 'saltenv={0}'.format(saltenv) if saltenv else ''\n url = salt.utils.data.decode(urlunparse(('file', '', path, '', query, '')))\n return 'salt://{0}'.format(url[len('file:///'):])\n", "def _check_proto(self, path):\n '''\n Make sure that this path is intended for the salt master and trim it\n '''\n if not path.startswith('salt://'):\n raise MinionError('Unsupported path: {0}'.format(path))\n file_path, saltenv = salt.utils.url.parse(path)\n return file_path\n", "def get_file(self,\n path,\n dest='',\n makedirs=False,\n saltenv='base',\n gzip=None,\n cachedir=None):\n '''\n Copies a file from the local files or master depending on\n implementation\n '''\n raise NotImplementedError\n", "def file_list_emptydirs(self, saltenv='base', prefix=''):\n '''\n List the empty dirs\n '''\n raise NotImplementedError\n", "def file_list(self, saltenv='base', prefix=''):\n '''\n This function must be overwritten\n '''\n return []\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.get_url
python
def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close()
Get a single file from a URL.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L458-L740
[ "def rename(src, dst):\n '''\n On Windows, os.rename() will fail with a WindowsError exception if a file\n exists at the destination path. This function checks for this error and if\n found, it deletes the destination path first.\n '''\n try:\n os.rename(src, dst)\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise\n try:\n os.remove(dst)\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n raise MinionError(\n 'Error: Unable to remove {0}: {1}'.format(\n dst,\n exc.strerror\n )\n )\n os.rename(src, dst)\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def get_file(self,\n path,\n dest='',\n makedirs=False,\n saltenv='base',\n gzip=None,\n cachedir=None):\n '''\n Copies a file from the local files or master depending on\n implementation\n '''\n raise NotImplementedError\n", "def _extrn_path(self, url, saltenv, cachedir=None):\n '''\n Return the extrn_filepath for a given url\n '''\n url_data = urlparse(url)\n if salt.utils.platform.is_windows():\n netloc = salt.utils.path.sanitize_win_path(url_data.netloc)\n else:\n netloc = url_data.netloc\n\n # Strip user:pass from URLs\n netloc = netloc.split('@')[-1]\n\n if cachedir is None:\n cachedir = self.opts['cachedir']\n elif not os.path.isabs(cachedir):\n cachedir = os.path.join(self.opts['cachedir'], cachedir)\n\n if url_data.query:\n file_name = '-'.join([url_data.path, url_data.query])\n else:\n file_name = url_data.path\n\n if len(file_name) > MAX_FILENAME_LENGTH:\n file_name = salt.utils.hashutils.sha256_digest(file_name)\n\n return salt.utils.path.join(\n cachedir,\n 'extrn_files',\n saltenv,\n netloc,\n file_name\n )\n", "def get_object(self, cont, obj, local_file=None, return_bin=False):\n '''\n Retrieve a file from Swift\n '''\n try:\n if local_file is None and return_bin is False:\n return False\n\n headers, body = self.conn.get_object(cont, obj, resp_chunk_size=65536)\n\n if return_bin is True:\n fp = sys.stdout\n else:\n dirpath = dirname(local_file)\n if dirpath and not isdir(dirpath):\n mkdirs(dirpath)\n fp = salt.utils.files.fopen(local_file, 'wb') # pylint: disable=resource-leakage\n\n read_length = 0\n for chunk in body:\n read_length += len(chunk)\n fp.write(chunk)\n fp.close()\n return True\n\n # ClientException\n # file/dir exceptions\n except Exception as exc:\n log.error('There was an error::')\n if hasattr(exc, 'code') and hasattr(exc, 'msg'):\n log.error(' Code: %s: %s', exc.code, exc.msg)\n log.error(' Content: \\n%s', getattr(exc, 'read', lambda: six.text_type(exc))())\n return False\n", "def s3_opt(key, default=None):\n '''\n Get value of s3.<key> from Minion config or from Pillar\n '''\n if 's3.' + key in self.opts:\n return self.opts['s3.' + key]\n try:\n return self.opts['pillar']['s3'][key]\n except (KeyError, TypeError):\n return default\n", "def swift_opt(key, default):\n '''\n Get value of <key> from Minion config or from Pillar\n '''\n if key in self.opts:\n return self.opts[key]\n try:\n return self.opts['pillar'][key]\n except (KeyError, TypeError):\n return default\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client.get_template
python
def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest
Cache a file then process it as a template
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L742-L792
[ "def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None):\n '''\n Pull a file down from the file server and store it in the minion\n file cache\n '''\n return self.get_url(\n path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash)\n", "def _extrn_path(self, url, saltenv, cachedir=None):\n '''\n Return the extrn_filepath for a given url\n '''\n url_data = urlparse(url)\n if salt.utils.platform.is_windows():\n netloc = salt.utils.path.sanitize_win_path(url_data.netloc)\n else:\n netloc = url_data.netloc\n\n # Strip user:pass from URLs\n netloc = netloc.split('@')[-1]\n\n if cachedir is None:\n cachedir = self.opts['cachedir']\n elif not os.path.isabs(cachedir):\n cachedir = os.path.join(self.opts['cachedir'], cachedir)\n\n if url_data.query:\n file_name = '-'.join([url_data.path, url_data.query])\n else:\n file_name = url_data.path\n\n if len(file_name) > MAX_FILENAME_LENGTH:\n file_name = salt.utils.hashutils.sha256_digest(file_name)\n\n return salt.utils.path.join(\n cachedir,\n 'extrn_files',\n saltenv,\n netloc,\n file_name\n )\n" ]
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
saltstack/salt
salt/fileclient.py
Client._extrn_path
python
def _extrn_path(self, url, saltenv, cachedir=None): ''' Return the extrn_filepath for a given url ''' url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc # Strip user:pass from URLs netloc = netloc.split('@')[-1] if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) if url_data.query: file_name = '-'.join([url_data.path, url_data.query]) else: file_name = url_data.path if len(file_name) > MAX_FILENAME_LENGTH: file_name = salt.utils.hashutils.sha256_digest(file_name) return salt.utils.path.join( cachedir, 'extrn_files', saltenv, netloc, file_name )
Return the extrn_filepath for a given url
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L794-L826
null
class Client(object): ''' Base class for Salt file interactions ''' def __init__(self, opts): self.opts = opts self.utils = salt.loader.utils(self.opts) self.serial = salt.payload.Serial(self.opts) # Add __setstate__ and __getstate__ so that the object may be # deep copied. It normally can't be deep copied because its # constructor requires an 'opts' parameter. # The TCP transport needs to be able to deep copy this class # due to 'salt.utils.context.ContextDict.clone'. def __setstate__(self, state): # This will polymorphically call __init__ # in the derived class. self.__init__(state['opts']) def __getstate__(self): return {'opts': self.opts} def _check_proto(self, path): ''' Make sure that this path is intended for the salt master and trim it ''' if not path.startswith('salt://'): raise MinionError('Unsupported path: {0}'.format(path)) file_path, saltenv = salt.utils.url.parse(path) return file_path def _file_local_list(self, dest): ''' Helper util to return a list of files in a directory ''' if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for root, dirs, files in salt.utils.path.os_walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist @contextlib.contextmanager def _cache_loc(self, path, saltenv='base', cachedir=None): ''' Return the local location to cache the file, cache dirs will be made ''' cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv, path) destdir = os.path.dirname(dest) with salt.utils.files.set_umask(0o077): # remove destdir if it is a regular file to avoid an OSError when # running os.makedirs below if os.path.isfile(destdir): os.remove(destdir) # ensure destdir exists try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise yield dest def get_cachedir(self, cachedir=None): if cachedir is None: cachedir = self.opts['cachedir'] elif not os.path.isabs(cachedir): cachedir = os.path.join(self.opts['cachedir'], cachedir) return cachedir def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files or master depending on implementation ''' raise NotImplementedError def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs ''' raise NotImplementedError def cache_file(self, path, saltenv='base', cachedir=None, source_hash=None): ''' Pull a file down from the file server and store it in the minion file cache ''' return self.get_url( path, '', True, saltenv, cachedir=cachedir, source_hash=source_hash) def cache_files(self, paths, saltenv='base', cachedir=None): ''' Download a list of files stored on the master and put them in the minion file cache ''' ret = [] if isinstance(paths, six.string_types): paths = paths.split(',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret def cache_master(self, saltenv='base', cachedir=None): ''' Download and cache all files on a master in a specified environment ''' ret = [] for path in self.file_list(saltenv): ret.append( self.cache_file( salt.utils.url.create(path), saltenv, cachedir=cachedir) ) return ret def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to make sure files start with this *directory*, use # '/' explicitly because the master (that's generating the # list of files) only runs on POSIX if not path.endswith('/'): path = path + '/' log.info( 'Caching directory \'%s\' for environment \'%s\'', path, saltenv ) # go through the list of all files finding ones that are in # the target directory and caching them for fn_ in self.file_list(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.strip() and fn_.startswith(path): if salt.utils.stringutils.check_include_exclude( fn_, include_pat, exclude_pat): fn_ = self.cache_file( salt.utils.url.create(fn_), saltenv, cachedir=cachedir) if fn_: ret.append(fn_) if include_empty: # Break up the path into a list containing the bottom-level # directory (the one being recursively copied) and the directories # preceding it # separated = string.rsplit(path, '/', 1) # if len(separated) != 2: # # No slashes in path. (So all files in saltenv will be copied) # prefix = '' # else: # prefix = separated[0] cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, 'files', saltenv) for fn_ in self.file_list_emptydirs(saltenv): fn_ = salt.utils.data.decode(fn_) if fn_.startswith(path): minion_dir = '{0}/{1}'.format(dest, fn_) if not os.path.isdir(minion_dir): os.makedirs(minion_dir) ret.append(minion_dir) return ret def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) shutil.copyfile(path, dest) return dest def file_local_list(self, saltenv='base'): ''' List files in the local minion files and localfiles caches ''' filesdest = os.path.join(self.opts['cachedir'], 'files', saltenv) localfilesdest = os.path.join(self.opts['cachedir'], 'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest)) def file_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def dir_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return [] def symlink_list(self, saltenv='base', prefix=''): ''' This function must be overwritten ''' return {} def is_cached(self, path, saltenv='base', cachedir=None): ''' Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string ''' if path.startswith('salt://'): path, senv = salt.utils.url.parse(path) if senv: saltenv = senv escaped = True if salt.utils.url.is_escaped(path) else False # also strip escape character '|' localsfilesdest = os.path.join( self.opts['cachedir'], 'localfiles', path.lstrip('|/')) filesdest = os.path.join( self.opts['cachedir'], 'files', saltenv, path.lstrip('|/')) extrndest = self._extrn_path(path, saltenv, cachedir=cachedir) if os.path.exists(filesdest): return salt.utils.url.escape(filesdest) if escaped else filesdest elif os.path.exists(localsfilesdest): return salt.utils.url.escape(localsfilesdest) \ if escaped \ else localsfilesdest elif os.path.exists(extrndest): return extrndest return '' def cache_dest(self, url, saltenv='base', cachedir=None): ''' Return the expected cache location for the specified URL and environment. ''' proto = urlparse(url).scheme if proto == '': # Local file path return url if proto == 'salt': url, senv = salt.utils.url.parse(url) if senv: saltenv = senv return salt.utils.path.join( self.opts['cachedir'], 'files', saltenv, url.lstrip('|/')) return self._extrn_path(url, saltenv, cachedir=cachedir) def list_states(self, saltenv): ''' Return a list of all available sls modules on the master for a given environment ''' states = set() for path in self.file_list(saltenv): if salt.utils.platform.is_windows(): path = path.replace('\\', '/') if path.endswith('.sls'): # is an sls module! if path.endswith('/init.sls'): states.add(path.replace('/', '.')[:-9]) else: states.add(path.replace('/', '.')[:-4]) return sorted(states) def get_state(self, sls, saltenv, cachedir=None): ''' Get a state file from the master and store it in the local minion cache; return the location of the file ''' if '.' in sls: sls = sls.replace('.', '/') sls_url = salt.utils.url.create(sls + '.sls') init_url = salt.utils.url.create(sls + '/init.sls') for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {'source': path, 'dest': dest} return {} def get_dir(self, path, dest='', saltenv='base', gzip=None, cachedir=None): ''' Get a directory recursively from the salt-master ''' ret = [] # Strip trailing slash path = self._check_proto(path).rstrip('/') # Break up the path into a list containing the bottom-level directory # (the one being recursively copied) and the directories preceding it separated = path.rsplit('/', 1) if len(separated) != 2: # No slashes in path. (This means all files in saltenv will be # copied) prefix = '' else: prefix = separated[0] # Copy files from master for fn_ in self.file_list(saltenv, prefix=path): # Prevent files in "salt://foobar/" (or salt://foo.sh) from # matching a path of "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') ret.append( self.get_file( salt.utils.url.create(fn_), '{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip ) ) # Replicate empty dirs from master try: for fn_ in self.file_list_emptydirs(saltenv, prefix=path): # Prevent an empty dir "salt://foobar/" from matching a path of # "salt://foo" try: if fn_[len(path)] != '/': continue except IndexError: continue # Remove the leading directories from path to derive # the relative path on the minion. minion_relpath = fn_[len(prefix):].lstrip('/') minion_mkdir = '{0}/{1}'.format(dest, minion_relpath) if not os.path.isdir(minion_mkdir): os.makedirs(minion_mkdir) ret.append(minion_mkdir) except TypeError: pass ret.sort() return ret def get_url(self, url, dest, makedirs=False, saltenv='base', no_cache=False, cachedir=None, source_hash=None): ''' Get a single file from a URL. ''' url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join( url_data.netloc, url_data.path).rstrip(os.sep) # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): if url_data.query or len(url_data.path) > 1 and not url_data.path.endswith('/'): strpath = url.split('/')[-1] else: strpath = 'index.html' if salt.utils.platform.is_windows(): strpath = salt.utils.path.sanitize_win_path(strpath) dest = os.path.join(dest, strpath) if url_scheme and url_scheme.lower() in string.ascii_lowercase: url_path = ':'.join((url_scheme, url_path)) url_scheme = 'file' if url_scheme in ('file', ''): # Local filesystem if not os.path.isabs(url_path): raise CommandExecutionError( 'Path \'{0}\' is not absolute'.format(url_path) ) if dest is None: with salt.utils.files.fopen(url_path, 'rb') as fp_: data = fp_.read() return data return url_path if url_scheme == 'salt': result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir) if result and dest is None: with salt.utils.files.fopen(result, 'rb') as fp_: data = fp_.read() return data return result if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: return '' elif not no_cache: dest = self._extrn_path(url, saltenv, cachedir=cachedir) if source_hash is not None: try: source_hash = source_hash.split('=')[-1] form = salt.utils.files.HASHES_REVMAP[len(source_hash)] if salt.utils.hashutils.get_hash(dest, form) == source_hash: log.debug( 'Cached copy of %s (%s) matches source_hash %s, ' 'skipping download', url, dest, source_hash ) return dest except (AttributeError, KeyError, IOError, OSError): pass destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) if url_data.scheme == 's3': try: def s3_opt(key, default=None): ''' Get value of s3.<key> from Minion config or from Pillar ''' if 's3.' + key in self.opts: return self.opts['s3.' + key] try: return self.opts['pillar']['s3'][key] except (KeyError, TypeError): return default self.utils['s3.query'](method='GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt('key'), keyid=s3_opt('keyid'), service_url=s3_opt('service_url'), verify_ssl=s3_opt('verify_ssl', True), location=s3_opt('location'), path_style=s3_opt('path_style', False), https_enable=s3_opt('https_enable', True)) return dest except Exception as exc: raise MinionError( 'Could not fetch from {0}. Exception: {1}'.format(url, exc) ) if url_data.scheme == 'ftp': try: ftp = ftplib.FTP() ftp.connect(url_data.hostname, url_data.port) ftp.login(url_data.username, url_data.password) remote_file_path = url_data.path.lstrip('/') with salt.utils.files.fopen(dest, 'wb') as fp_: ftp.retrbinary('RETR {0}'.format(remote_file_path), fp_.write) ftp.quit() return dest except Exception as exc: raise MinionError('Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc)) if url_data.scheme == 'swift': try: def swift_opt(key, default): ''' Get value of <key> from Minion config or from Pillar ''' if key in self.opts: return self.opts[key] try: return self.opts['pillar'][key] except (KeyError, TypeError): return default swift_conn = SaltSwift(swift_opt('keystone.user', None), swift_opt('keystone.tenant', None), swift_opt('keystone.auth_url', None), swift_opt('keystone.password', None)) swift_conn.get_object(url_data.netloc, url_data.path[1:], dest) return dest except Exception: raise MinionError('Could not fetch from {0}'.format(url)) get_kwargs = {} if url_data.username is not None \ and url_data.scheme in ('http', 'https'): netloc = url_data.netloc at_sign_pos = netloc.rfind('@') if at_sign_pos != -1: netloc = netloc[at_sign_pos + 1:] fixed_url = urlunparse( (url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment)) get_kwargs['auth'] = (url_data.username, url_data.password) else: fixed_url = url destfp = None try: # Tornado calls streaming_callback on redirect response bodies. # But we need streaming to support fetching large files (> RAM # avail). Here we are working around this by disabling recording # the body for redirections. The issue is fixed in Tornado 4.3.0 # so on_header callback could be removed when we'll deprecate # Tornado<4.3.0. See #27093 and #30431 for details. # Use list here to make it writable inside the on_header callback. # Simple bool doesn't work here: on_header creates a new local # variable instead. This could be avoided in Py3 with 'nonlocal' # statement. There is no Py2 alternative for this. # # write_body[0] is used by the on_chunk callback to tell it whether # or not we need to write the body of the request to disk. For # 30x redirects we set this to False because we don't want to # write the contents to disk, as we will need to wait until we # get to the redirected URL. # # write_body[1] will contain a tornado.httputil.HTTPHeaders # instance that we will use to parse each header line. We # initialize this to False, and after we parse the status line we # will replace it with the HTTPHeaders instance. If/when we have # found the encoding used in the request, we set this value to # False to signify that we are done parsing. # # write_body[2] is where the encoding will be stored write_body = [None, False, None] def on_header(hdr): if write_body[1] is not False and write_body[2] is None: if not hdr.strip() and 'Content-Type' not in write_body[1]: # If write_body[0] is True, then we are not following a # redirect (initial response was a 200 OK). So there is # no need to reset write_body[0]. if write_body[0] is not True: # We are following a redirect, so we need to reset # write_body[0] so that we properly follow it. write_body[0] = None # We don't need the HTTPHeaders object anymore write_body[1] = False return # Try to find out what content type encoding is used if # this is a text file write_body[1].parse_line(hdr) # pylint: disable=no-member if 'Content-Type' in write_body[1]: content_type = write_body[1].get('Content-Type') # pylint: disable=no-member if not content_type.startswith('text'): write_body[1] = write_body[2] = False else: encoding = 'utf-8' fields = content_type.split(';') for field in fields: if 'encoding' in field: encoding = field.split('encoding=')[-1] write_body[2] = encoding # We have found our encoding. Stop processing headers. write_body[1] = False # If write_body[0] is False, this means that this # header is a 30x redirect, so we need to reset # write_body[0] to None so that we parse the HTTP # status code from the redirect target. Additionally, # we need to reset write_body[2] so that we inspect the # headers for the Content-Type of the URL we're # following. if write_body[0] is write_body[1] is False: write_body[0] = write_body[2] = None # Check the status line of the HTTP request if write_body[0] is None: try: hdr = parse_response_start_line(hdr) except HTTPInputError: # Not the first line, do nothing return write_body[0] = hdr.code not in [301, 302, 303, 307] write_body[1] = HTTPHeaders() if no_cache: result = [] def on_chunk(chunk): if write_body[0]: if write_body[2]: chunk = chunk.decode(write_body[2]) result.append(chunk) else: dest_tmp = u"{0}.part".format(dest) # We need an open filehandle to use in the on_chunk callback, # that's why we're not using a with clause here. destfp = salt.utils.files.fopen(dest_tmp, 'wb') # pylint: disable=resource-leakage def on_chunk(chunk): if write_body[0]: destfp.write(chunk) query = salt.utils.http.query( fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs ) if 'handle' not in query: raise MinionError('Error: {0} reading {1}'.format(query['error'], url)) if no_cache: if write_body[2]: return ''.join(result) return b''.join(result) else: destfp.close() destfp = None salt.utils.files.rename(dest_tmp, dest) return dest except HTTPError as exc: raise MinionError('HTTP error {0} reading {1}: {3}'.format( exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code])) except URLError as exc: raise MinionError('Error reading {0}: {1}'.format(url, exc.reason)) finally: if destfp is not None: destfp.close() def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): ''' Cache a file then process it as a template ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') kwargs['saltenv'] = saltenv url_data = urlparse(url) sfn = self.cache_file(url, saltenv, cachedir=cachedir) if not sfn or not os.path.exists(sfn): return '' if template in salt.utils.templates.TEMPLATE_REGISTRY: data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) else: log.error( 'Attempted to render template with unavailable engine %s', template ) return '' if not data['result']: # Failed to render the template log.error('Failed to render template with error: %s', data['data']) return '' if not dest: # No destination passed, set the dest as an extrn_files cache dest = self._extrn_path(url, saltenv, cachedir=cachedir) # If Salt generated the dest name, create any required dirs makedirs = True destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: os.makedirs(destdir) else: salt.utils.files.safe_rm(data['data']) return '' shutil.move(data['data'], dest) return dest
saltstack/salt
salt/fileclient.py
PillarClient._find_file
python
def _find_file(self, path, saltenv='base'): ''' Locate the file path ''' fnd = {'path': '', 'rel': ''} if salt.utils.url.is_escaped(path): # The path arguments are escaped path = salt.utils.url.unescape(path) for root in self.opts['pillar_roots'].get(saltenv, []): full = os.path.join(root, path) if os.path.isfile(full): fnd['path'] = full fnd['rel'] = path return fnd return fnd
Locate the file path
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L833-L849
[ "def is_escaped(url):\n '''\n test whether `url` is escaped with `|`\n '''\n scheme = urlparse(url).scheme\n if not scheme:\n return url.startswith('|')\n elif scheme == 'salt':\n path, saltenv = parse(url)\n if salt.utils.platform.is_windows() and '|' in url:\n return path.startswith('_')\n else:\n return path.startswith('|')\n else:\n return False\n" ]
class PillarClient(Client): ''' Used by pillar to handle fileclient requests ''' def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files ''' path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get('path') if not fnd_path: return '' return fnd_path def file_list(self, saltenv='base', prefix=''): ''' Return a list of files in the given environment with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] for fname in files: relpath = os.path.relpath(os.path.join(root, fname), path) ret.append(salt.utils.data.decode(relpath)) return ret def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] if not dirs and not files: ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def dir_list(self, saltenv='base', prefix=''): ''' List the dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def __get_file_path(self, path, saltenv='base'): ''' Return either a file path or the result of a remote find_file call. ''' try: path = self._check_proto(path) except MinionError as err: # Local file path if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return None else: return path return self._find_file(path, saltenv) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] except TypeError: # Local file path fnd_path = fnd hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret def hash_and_stat_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret, None try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] fnd_stat = fnd.get('stat') except TypeError: # Local file path fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: fnd_stat = None hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret, fnd_stat def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' return self.file_list(saltenv) def master_opts(self): ''' Return the master opts data ''' return self.opts def envs(self): ''' Return the available environments ''' ret = [] for saltenv in self.opts['pillar_roots']: ret.append(saltenv) return ret def master_tops(self): ''' Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environment yet. It's worth noting that originally this fn started with if 'external_nodes' not in opts: return {} So since external_nodes is gone now, we are just returning the empty dict. ''' return {}
saltstack/salt
salt/fileclient.py
PillarClient.get_file
python
def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files ''' path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get('path') if not fnd_path: return '' return fnd_path
Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L851-L868
[ "def _check_proto(self, path):\n '''\n Make sure that this path is intended for the salt master and trim it\n '''\n if not path.startswith('salt://'):\n raise MinionError('Unsupported path: {0}'.format(path))\n file_path, saltenv = salt.utils.url.parse(path)\n return file_path\n", "def _find_file(self, path, saltenv='base'):\n '''\n Locate the file path\n '''\n fnd = {'path': '',\n 'rel': ''}\n\n if salt.utils.url.is_escaped(path):\n # The path arguments are escaped\n path = salt.utils.url.unescape(path)\n for root in self.opts['pillar_roots'].get(saltenv, []):\n full = os.path.join(root, path)\n if os.path.isfile(full):\n fnd['path'] = full\n fnd['rel'] = path\n return fnd\n return fnd\n" ]
class PillarClient(Client): ''' Used by pillar to handle fileclient requests ''' def _find_file(self, path, saltenv='base'): ''' Locate the file path ''' fnd = {'path': '', 'rel': ''} if salt.utils.url.is_escaped(path): # The path arguments are escaped path = salt.utils.url.unescape(path) for root in self.opts['pillar_roots'].get(saltenv, []): full = os.path.join(root, path) if os.path.isfile(full): fnd['path'] = full fnd['rel'] = path return fnd return fnd def file_list(self, saltenv='base', prefix=''): ''' Return a list of files in the given environment with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] for fname in files: relpath = os.path.relpath(os.path.join(root, fname), path) ret.append(salt.utils.data.decode(relpath)) return ret def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] if not dirs and not files: ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def dir_list(self, saltenv='base', prefix=''): ''' List the dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def __get_file_path(self, path, saltenv='base'): ''' Return either a file path or the result of a remote find_file call. ''' try: path = self._check_proto(path) except MinionError as err: # Local file path if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return None else: return path return self._find_file(path, saltenv) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] except TypeError: # Local file path fnd_path = fnd hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret def hash_and_stat_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret, None try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] fnd_stat = fnd.get('stat') except TypeError: # Local file path fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: fnd_stat = None hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret, fnd_stat def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' return self.file_list(saltenv) def master_opts(self): ''' Return the master opts data ''' return self.opts def envs(self): ''' Return the available environments ''' ret = [] for saltenv in self.opts['pillar_roots']: ret.append(saltenv) return ret def master_tops(self): ''' Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environment yet. It's worth noting that originally this fn started with if 'external_nodes' not in opts: return {} So since external_nodes is gone now, we are just returning the empty dict. ''' return {}
saltstack/salt
salt/fileclient.py
PillarClient.file_list
python
def file_list(self, saltenv='base', prefix=''): ''' Return a list of files in the given environment with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] for fname in files: relpath = os.path.relpath(os.path.join(root, fname), path) ret.append(salt.utils.data.decode(relpath)) return ret
Return a list of files in the given environment with optional relative prefix path to limit directory traversal
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L870-L886
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n", "def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n" ]
class PillarClient(Client): ''' Used by pillar to handle fileclient requests ''' def _find_file(self, path, saltenv='base'): ''' Locate the file path ''' fnd = {'path': '', 'rel': ''} if salt.utils.url.is_escaped(path): # The path arguments are escaped path = salt.utils.url.unescape(path) for root in self.opts['pillar_roots'].get(saltenv, []): full = os.path.join(root, path) if os.path.isfile(full): fnd['path'] = full fnd['rel'] = path return fnd return fnd def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files ''' path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get('path') if not fnd_path: return '' return fnd_path def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] if not dirs and not files: ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def dir_list(self, saltenv='base', prefix=''): ''' List the dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def __get_file_path(self, path, saltenv='base'): ''' Return either a file path or the result of a remote find_file call. ''' try: path = self._check_proto(path) except MinionError as err: # Local file path if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return None else: return path return self._find_file(path, saltenv) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] except TypeError: # Local file path fnd_path = fnd hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret def hash_and_stat_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret, None try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] fnd_stat = fnd.get('stat') except TypeError: # Local file path fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: fnd_stat = None hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret, fnd_stat def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' return self.file_list(saltenv) def master_opts(self): ''' Return the master opts data ''' return self.opts def envs(self): ''' Return the available environments ''' ret = [] for saltenv in self.opts['pillar_roots']: ret.append(saltenv) return ret def master_tops(self): ''' Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environment yet. It's worth noting that originally this fn started with if 'external_nodes' not in opts: return {} So since external_nodes is gone now, we are just returning the empty dict. ''' return {}
saltstack/salt
salt/fileclient.py
PillarClient.__get_file_path
python
def __get_file_path(self, path, saltenv='base'): ''' Return either a file path or the result of a remote find_file call. ''' try: path = self._check_proto(path) except MinionError as err: # Local file path if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return None else: return path return self._find_file(path, saltenv)
Return either a file path or the result of a remote find_file call.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L919-L935
[ "def _check_proto(self, path):\n '''\n Make sure that this path is intended for the salt master and trim it\n '''\n if not path.startswith('salt://'):\n raise MinionError('Unsupported path: {0}'.format(path))\n file_path, saltenv = salt.utils.url.parse(path)\n return file_path\n", "def _find_file(self, path, saltenv='base'):\n '''\n Locate the file path\n '''\n fnd = {'path': '',\n 'rel': ''}\n\n if salt.utils.url.is_escaped(path):\n # The path arguments are escaped\n path = salt.utils.url.unescape(path)\n for root in self.opts['pillar_roots'].get(saltenv, []):\n full = os.path.join(root, path)\n if os.path.isfile(full):\n fnd['path'] = full\n fnd['rel'] = path\n return fnd\n return fnd\n" ]
class PillarClient(Client): ''' Used by pillar to handle fileclient requests ''' def _find_file(self, path, saltenv='base'): ''' Locate the file path ''' fnd = {'path': '', 'rel': ''} if salt.utils.url.is_escaped(path): # The path arguments are escaped path = salt.utils.url.unescape(path) for root in self.opts['pillar_roots'].get(saltenv, []): full = os.path.join(root, path) if os.path.isfile(full): fnd['path'] = full fnd['rel'] = path return fnd return fnd def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files ''' path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get('path') if not fnd_path: return '' return fnd_path def file_list(self, saltenv='base', prefix=''): ''' Return a list of files in the given environment with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] for fname in files: relpath = os.path.relpath(os.path.join(root, fname), path) ret.append(salt.utils.data.decode(relpath)) return ret def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] if not dirs and not files: ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def dir_list(self, saltenv='base', prefix=''): ''' List the dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] except TypeError: # Local file path fnd_path = fnd hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret def hash_and_stat_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret, None try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] fnd_stat = fnd.get('stat') except TypeError: # Local file path fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: fnd_stat = None hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret, fnd_stat def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' return self.file_list(saltenv) def master_opts(self): ''' Return the master opts data ''' return self.opts def envs(self): ''' Return the available environments ''' ret = [] for saltenv in self.opts['pillar_roots']: ret.append(saltenv) return ret def master_tops(self): ''' Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environment yet. It's worth noting that originally this fn started with if 'external_nodes' not in opts: return {} So since external_nodes is gone now, we are just returning the empty dict. ''' return {}
saltstack/salt
salt/fileclient.py
PillarClient.hash_file
python
def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] except TypeError: # Local file path fnd_path = fnd hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret
Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L937-L958
[ "def __get_file_path(self, path, saltenv='base'):\n '''\n Return either a file path or the result of a remote find_file call.\n '''\n try:\n path = self._check_proto(path)\n except MinionError as err:\n # Local file path\n if not os.path.isfile(path):\n log.warning(\n 'specified file %s is not present to generate hash: %s',\n path, err\n )\n return None\n else:\n return path\n return self._find_file(path, saltenv)\n" ]
class PillarClient(Client): ''' Used by pillar to handle fileclient requests ''' def _find_file(self, path, saltenv='base'): ''' Locate the file path ''' fnd = {'path': '', 'rel': ''} if salt.utils.url.is_escaped(path): # The path arguments are escaped path = salt.utils.url.unescape(path) for root in self.opts['pillar_roots'].get(saltenv, []): full = os.path.join(root, path) if os.path.isfile(full): fnd['path'] = full fnd['rel'] = path return fnd return fnd def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files ''' path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get('path') if not fnd_path: return '' return fnd_path def file_list(self, saltenv='base', prefix=''): ''' Return a list of files in the given environment with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] for fname in files: relpath = os.path.relpath(os.path.join(root, fname), path) ret.append(salt.utils.data.decode(relpath)) return ret def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] if not dirs and not files: ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def dir_list(self, saltenv='base', prefix=''): ''' List the dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def __get_file_path(self, path, saltenv='base'): ''' Return either a file path or the result of a remote find_file call. ''' try: path = self._check_proto(path) except MinionError as err: # Local file path if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return None else: return path return self._find_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret, None try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] fnd_stat = fnd.get('stat') except TypeError: # Local file path fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: fnd_stat = None hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret, fnd_stat def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' return self.file_list(saltenv) def master_opts(self): ''' Return the master opts data ''' return self.opts def envs(self): ''' Return the available environments ''' ret = [] for saltenv in self.opts['pillar_roots']: ret.append(saltenv) return ret def master_tops(self): ''' Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environment yet. It's worth noting that originally this fn started with if 'external_nodes' not in opts: return {} So since external_nodes is gone now, we are just returning the empty dict. ''' return {}
saltstack/salt
salt/fileclient.py
PillarClient.hash_and_stat_file
python
def hash_and_stat_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret, None try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] fnd_stat = fnd.get('stat') except TypeError: # Local file path fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: fnd_stat = None hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret, fnd_stat
Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L960-L989
[ "def __get_file_path(self, path, saltenv='base'):\n '''\n Return either a file path or the result of a remote find_file call.\n '''\n try:\n path = self._check_proto(path)\n except MinionError as err:\n # Local file path\n if not os.path.isfile(path):\n log.warning(\n 'specified file %s is not present to generate hash: %s',\n path, err\n )\n return None\n else:\n return path\n return self._find_file(path, saltenv)\n" ]
class PillarClient(Client): ''' Used by pillar to handle fileclient requests ''' def _find_file(self, path, saltenv='base'): ''' Locate the file path ''' fnd = {'path': '', 'rel': ''} if salt.utils.url.is_escaped(path): # The path arguments are escaped path = salt.utils.url.unescape(path) for root in self.opts['pillar_roots'].get(saltenv, []): full = os.path.join(root, path) if os.path.isfile(full): fnd['path'] = full fnd['rel'] = path return fnd return fnd def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files ''' path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get('path') if not fnd_path: return '' return fnd_path def file_list(self, saltenv='base', prefix=''): ''' Return a list of files in the given environment with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] for fname in files: relpath = os.path.relpath(os.path.join(root, fname), path) ret.append(salt.utils.data.decode(relpath)) return ret def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] if not dirs and not files: ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def dir_list(self, saltenv='base', prefix=''): ''' List the dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def __get_file_path(self, path, saltenv='base'): ''' Return either a file path or the result of a remote find_file call. ''' try: path = self._check_proto(path) except MinionError as err: # Local file path if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return None else: return path return self._find_file(path, saltenv) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] except TypeError: # Local file path fnd_path = fnd hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' return self.file_list(saltenv) def master_opts(self): ''' Return the master opts data ''' return self.opts def envs(self): ''' Return the available environments ''' ret = [] for saltenv in self.opts['pillar_roots']: ret.append(saltenv) return ret def master_tops(self): ''' Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environment yet. It's worth noting that originally this fn started with if 'external_nodes' not in opts: return {} So since external_nodes is gone now, we are just returning the empty dict. ''' return {}
saltstack/salt
salt/fileclient.py
PillarClient.envs
python
def envs(self): ''' Return the available environments ''' ret = [] for saltenv in self.opts['pillar_roots']: ret.append(saltenv) return ret
Return the available environments
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1003-L1010
null
class PillarClient(Client): ''' Used by pillar to handle fileclient requests ''' def _find_file(self, path, saltenv='base'): ''' Locate the file path ''' fnd = {'path': '', 'rel': ''} if salt.utils.url.is_escaped(path): # The path arguments are escaped path = salt.utils.url.unescape(path) for root in self.opts['pillar_roots'].get(saltenv, []): full = os.path.join(root, path) if os.path.isfile(full): fnd['path'] = full fnd['rel'] = path return fnd return fnd def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files ''' path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get('path') if not fnd_path: return '' return fnd_path def file_list(self, saltenv='base', prefix=''): ''' Return a list of files in the given environment with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] for fname in files: relpath = os.path.relpath(os.path.join(root, fname), path) ret.append(salt.utils.data.decode(relpath)) return ret def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): # Don't walk any directories that match file_ignore_regex or glob dirs[:] = [d for d in dirs if not salt.fileserver.is_file_ignored(self.opts, d)] if not dirs and not files: ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def dir_list(self, saltenv='base', prefix=''): ''' List the dirs in the pillar_roots with optional relative prefix path to limit directory traversal ''' ret = [] prefix = prefix.strip('/') for path in self.opts['pillar_roots'].get(saltenv, []): for root, dirs, files in salt.utils.path.os_walk( os.path.join(path, prefix), followlinks=True ): ret.append(salt.utils.data.decode(os.path.relpath(root, path))) return ret def __get_file_path(self, path, saltenv='base'): ''' Return either a file path or the result of a remote find_file call. ''' try: path = self._check_proto(path) except MinionError as err: # Local file path if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return None else: return path return self._find_file(path, saltenv) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] except TypeError: # Local file path fnd_path = fnd hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret def hash_and_stat_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file in the pillar_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found. ''' ret = {} fnd = self.__get_file_path(path, saltenv) if fnd is None: return ret, None try: # Remote file path (self._find_file() invoked) fnd_path = fnd['path'] fnd_stat = fnd.get('stat') except TypeError: # Local file path fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: fnd_stat = None hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(fnd_path, form=hash_type) ret['hash_type'] = hash_type return ret, fnd_stat def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' return self.file_list(saltenv) def master_opts(self): ''' Return the master opts data ''' return self.opts def master_tops(self): ''' Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environment yet. It's worth noting that originally this fn started with if 'external_nodes' not in opts: return {} So since external_nodes is gone now, we are just returning the empty dict. ''' return {}
saltstack/salt
salt/fileclient.py
RemoteClient._refresh_channel
python
def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel
Reset the channel, in the event of an interruption
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1041-L1046
null
class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
saltstack/salt
salt/fileclient.py
RemoteClient.get_file
python
def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest
Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1064-L1262
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n", "def rm_rf(path):\n '''\n Platform-independent recursive delete. Includes code from\n http://stackoverflow.com/a/2656405\n '''\n def _onerror(func, path, exc_info):\n '''\n Error handler for `shutil.rmtree`.\n\n If the error is due to an access error (read only file)\n it attempts to add write permission and then retries.\n\n If the error is for another reason it re-raises the error.\n\n Usage : `shutil.rmtree(path, onerror=onerror)`\n '''\n if salt.utils.platform.is_windows() and not os.access(path, os.W_OK):\n # Is the error an access error ?\n os.chmod(path, stat.S_IWUSR)\n func(path)\n else:\n raise # pylint: disable=E0704\n if os.path.islink(path) or not os.path.isdir(path):\n os.remove(path)\n else:\n if salt.utils.platform.is_windows():\n try:\n path = salt.utils.stringutils.to_unicode(path)\n except TypeError:\n pass\n shutil.rmtree(path, onerror=_onerror)\n", "def atomic_open(filename, mode='w'):\n '''\n Works like a regular `open()` but writes updates into a temporary\n file instead of the given file and moves it over when the file is\n closed. The file returned behaves as if it was a regular Python\n '''\n if mode in ('r', 'rb', 'r+', 'rb+', 'a', 'ab'):\n raise TypeError('Read or append modes don\\'t work with atomic_open')\n kwargs = {\n 'prefix': '.___atomic_write',\n 'dir': os.path.dirname(filename),\n 'delete': False,\n }\n if six.PY3 and 'b' not in mode:\n kwargs['newline'] = ''\n ntf = tempfile.NamedTemporaryFile(mode, **kwargs)\n return _AtomicWFile(ntf, ntf.name, filename)\n", "def uncompress(data):\n buf = BytesIO(data)\n with open_fileobj(buf, 'rb') as igz:\n unc = igz.read()\n return unc\n", "def split_env(url):\n '''\n remove the saltenv query parameter from a 'salt://' url\n '''\n if not url.startswith('salt://'):\n return url, None\n\n path, senv = parse(url)\n return create(path), senv\n", "def _check_proto(self, path):\n '''\n Make sure that this path is intended for the salt master and trim it\n '''\n if not path.startswith('salt://'):\n raise MinionError('Unsupported path: {0}'.format(path))\n file_path, saltenv = salt.utils.url.parse(path)\n return file_path\n", "def _refresh_channel(self):\n '''\n Reset the channel, in the event of an interruption\n '''\n self.channel = salt.transport.client.ReqChannel.factory(self.opts)\n return self.channel\n", "def hash_file(self, path, saltenv='base'):\n '''\n Return the hash of a file, to get the hash of a file on the salt\n master file server prepend the path with salt://<file on server>\n otherwise, prepend the file with / for a local file.\n '''\n return self.__hash_and_stat_file(path, saltenv)\n", "def hash_and_stat_file(self, path, saltenv='base'):\n '''\n The same as hash_file, but also return the file's mode, or None if no\n mode data is present.\n '''\n hash_result = self.hash_file(path, saltenv)\n try:\n path = self._check_proto(path)\n except MinionError as err:\n if not os.path.isfile(path):\n return hash_result, None\n else:\n try:\n return hash_result, list(os.stat(path))\n except Exception:\n return hash_result, None\n load = {'path': path,\n 'saltenv': saltenv,\n 'cmd': '_file_find'}\n fnd = self.channel.send(load)\n try:\n stat_result = fnd.get('stat')\n except AttributeError:\n stat_result = None\n return hash_result, stat_result\n" ]
class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
saltstack/salt
salt/fileclient.py
RemoteClient.dir_list
python
def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
List the dirs on the master
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1284-L1292
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n" ]
class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
saltstack/salt
salt/fileclient.py
RemoteClient.__hash_and_stat_file
python
def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load)
Common code for hashing and stating files
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1304-L1326
[ "def _check_proto(self, path):\n '''\n Make sure that this path is intended for the salt master and trim it\n '''\n if not path.startswith('salt://'):\n raise MinionError('Unsupported path: {0}'.format(path))\n file_path, saltenv = salt.utils.url.parse(path)\n return file_path\n" ]
class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
saltstack/salt
salt/fileclient.py
RemoteClient.hash_and_stat_file
python
def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result
The same as hash_file, but also return the file's mode, or None if no mode data is present.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1336-L1360
[ "def _check_proto(self, path):\n '''\n Make sure that this path is intended for the salt master and trim it\n '''\n if not path.startswith('salt://'):\n raise MinionError('Unsupported path: {0}'.format(path))\n file_path, saltenv = salt.utils.url.parse(path)\n return file_path\n", "def hash_file(self, path, saltenv='base'):\n '''\n Return the hash of a file, to get the hash of a file on the salt\n master file server prepend the path with salt://<file on server>\n otherwise, prepend the file with / for a local file.\n '''\n return self.__hash_and_stat_file(path, saltenv)\n" ]
class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
saltstack/salt
salt/fileclient.py
RemoteClient.list_env
python
def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
Return a list of the files in the file server's specified environment
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1362-L1369
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n" ]
class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
saltstack/salt
salt/fileclient.py
RemoteClient.envs
python
def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
Return a list of available environments
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1371-L1377
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n" ]
class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
saltstack/salt
salt/fileclient.py
RemoteClient.master_tops
python
def master_tops(self): ''' Return the metadata derived from the master_tops system ''' log.debug( 'The _ext_nodes master function has been renamed to _master_tops. ' 'To ensure compatibility when using older Salt masters we will ' 'continue to invoke the function as _ext_nodes until the ' 'Magnesium release.' ) # TODO: Change back to _master_tops # for Magnesium release load = {'cmd': '_ext_nodes', 'id': self.opts['id'], 'opts': self.opts} if self.auth: load['tok'] = self.auth.gen_token(b'salt') return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
Return the metadata derived from the master_tops system
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1387-L1405
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n" ]
class RemoteClient(Client): ''' Interact with the salt master file server. ''' def __init__(self, opts): Client.__init__(self, opts) self._closing = False self.channel = salt.transport.client.ReqChannel.factory(self.opts) if hasattr(self.channel, 'auth'): self.auth = self.channel.auth else: self.auth = '' def _refresh_channel(self): ''' Reset the channel, in the event of an interruption ''' self.channel = salt.transport.client.ReqChannel.factory(self.opts) return self.channel def __del__(self): self.destroy() def destroy(self): if self._closing: return self._closing = True channel = None try: channel = self.channel except AttributeError: pass if channel is not None: channel.close() def get_file(self, path, dest='', makedirs=False, saltenv='base', gzip=None, cachedir=None): ''' Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache ''' path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not salt.utils.platform.is_windows(): hash_server, stat_server = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_server = None else: hash_server = self.hash_file(path, saltenv) mode_server = None # Check if file exists on server, before creating files and # directories if hash_server == '': log.debug( 'Could not find file \'%s\' in saltenv \'%s\'', path, saltenv ) return False # If dest is a directory, rewrite dest with filename if dest is not None \ and (os.path.isdir(dest) or dest.endswith(('/', '\\'))): dest = os.path.join(dest, os.path.basename(path)) log.debug( 'In saltenv \'%s\', \'%s\' is a directory. Changing dest to ' '\'%s\'', saltenv, os.path.dirname(dest), dest ) # Hash compare local copy with master and skip download # if no difference found. dest2check = dest if not dest2check: rel_path = self._check_proto(path) log.debug( 'In saltenv \'%s\', looking at rel_path \'%s\' to resolve ' '\'%s\'', saltenv, rel_path, path ) with self._cache_loc( rel_path, saltenv, cachedir=cachedir) as cache_dest: dest2check = cache_dest log.debug( 'In saltenv \'%s\', ** considering ** path \'%s\' to resolve ' '\'%s\'', saltenv, dest2check, path ) if dest2check and os.path.isfile(dest2check): if not salt.utils.platform.is_windows(): hash_local, stat_local = \ self.hash_and_stat_file(dest2check, saltenv) try: mode_local = stat_local[0] except (IndexError, TypeError): mode_local = None else: hash_local = self.hash_file(dest2check, saltenv) mode_local = None if hash_local == hash_server: return dest2check log.debug( 'Fetching file from saltenv \'%s\', ** attempting ** \'%s\'', saltenv, path ) d_tries = 0 transport_tries = 0 path = self._check_proto(path) load = {'path': path, 'saltenv': saltenv, 'cmd': '_serve_file'} if gzip: gzip = int(gzip) load['gzip'] = gzip fn_ = None if dest: destdir = os.path.dirname(dest) if not os.path.isdir(destdir): if makedirs: try: os.makedirs(destdir) except OSError as exc: if exc.errno != errno.EEXIST: # ignore if it was there already raise else: return False # We need an open filehandle here, that's why we're not using a # with clause: fn_ = salt.utils.files.fopen(dest, 'wb+') # pylint: disable=resource-leakage else: log.debug('No dest file found') while True: if not fn_: load['loc'] = 0 else: load['loc'] = fn_.tell() data = self.channel.send(load, raw=True) if six.PY3: # Sometimes the source is local (eg when using # 'salt.fileserver.FSChan'), in which case the keys are # already strings. Sometimes the source is remote, in which # case the keys are bytes due to raw mode. Standardize on # strings for the top-level keys to simplify things. data = decode_dict_keys_to_str(data) try: if not data['data']: if not fn_ and data['dest']: # This is a 0 byte file on the master with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest with salt.utils.files.fopen(cache_dest, 'wb+') as ofile: ofile.write(data['data']) if 'hsum' in data and d_tries < 3: # Master has prompted a file verification, if the # verification fails, re-download the file. Try 3 times d_tries += 1 hsum = salt.utils.hashutils.get_hash(dest, salt.utils.stringutils.to_str(data.get('hash_type', b'md5'))) if hsum != data['hsum']: log.warning( 'Bad download of file %s, attempt %d of 3', path, d_tries ) continue break if not fn_: with self._cache_loc( data['dest'], saltenv, cachedir=cachedir) as cache_dest: dest = cache_dest # If a directory was formerly cached at this path, then # remove it to avoid a traceback trying to write the file if os.path.isdir(dest): salt.utils.files.rm_rf(dest) fn_ = salt.utils.atomicfile.atomic_open(dest, 'wb+') if data.get('gzip', None): data = salt.utils.gzip_util.uncompress(data['data']) else: data = data['data'] if six.PY3 and isinstance(data, str): data = data.encode() fn_.write(data) except (TypeError, KeyError) as exc: try: data_type = type(data).__name__ except AttributeError: # Shouldn't happen, but don't let this cause a traceback. data_type = six.text_type(type(data)) transport_tries += 1 log.warning( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, attempt %d of 3', data, data_type, exc, transport_tries ) self._refresh_channel() if transport_tries > 3: log.error( 'Data transport is broken, got: %s, type: %s, ' 'exception: %s, retry attempts exhausted', data, data_type, exc ) break if fn_: fn_.close() log.info( 'Fetching file from saltenv \'%s\', ** done ** \'%s\'', saltenv, path ) else: log.debug( 'In saltenv \'%s\', we are ** missing ** the file \'%s\'', saltenv, path ) return dest def file_list(self, saltenv='base', prefix=''): ''' List the files on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def file_list_emptydirs(self, saltenv='base', prefix=''): ''' List the empty dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_file_list_emptydirs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def dir_list(self, saltenv='base', prefix=''): ''' List the dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_dir_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def symlink_list(self, saltenv='base', prefix=''): ''' List symlinked files and dirs on the master ''' load = {'saltenv': saltenv, 'prefix': prefix, 'cmd': '_symlink_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def __hash_and_stat_file(self, path, saltenv='base'): ''' Common code for hashing and stating files ''' try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ) return {}, None else: ret = {} hash_type = self.opts.get('hash_type', 'md5') ret['hsum'] = salt.utils.hashutils.get_hash(path, form=hash_type) ret['hash_type'] = hash_type return ret load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_hash'} return self.channel.send(load) def hash_file(self, path, saltenv='base'): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. ''' return self.__hash_and_stat_file(path, saltenv) def hash_and_stat_file(self, path, saltenv='base'): ''' The same as hash_file, but also return the file's mode, or None if no mode data is present. ''' hash_result = self.hash_file(path, saltenv) try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): return hash_result, None else: try: return hash_result, list(os.stat(path)) except Exception: return hash_result, None load = {'path': path, 'saltenv': saltenv, 'cmd': '_file_find'} fnd = self.channel.send(load) try: stat_result = fnd.get('stat') except AttributeError: stat_result = None return hash_result, stat_result def list_env(self, saltenv='base'): ''' Return a list of the files in the file server's specified environment ''' load = {'saltenv': saltenv, 'cmd': '_file_list'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load) def master_opts(self): ''' Return the master opts data ''' load = {'cmd': '_master_opts'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
saltstack/salt
salt/states/saltsupport.py
SaltSupportState.check_destination
python
def check_destination(self, location, group): ''' Check destination for the archives. :return: ''' # Pre-create destination, since rsync will # put one file named as group try: destination = os.path.join(location, group) if os.path.exists(destination) and not os.path.isdir(destination): raise salt.exceptions.SaltException('Destination "{}" should be directory!'.format(destination)) if not os.path.exists(destination): os.makedirs(destination) log.debug('Created destination directory for archives: %s', destination) else: log.debug('Archives destination directory %s already exists', destination) except OSError as err: log.error(err)
Check destination for the archives. :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltsupport.py#L96-L113
null
class SaltSupportState(object): ''' Salt-support. ''' EXPORTED = ['collected', 'taken'] def get_kwargs(self, data): kwargs = {} for keyset in data: kwargs.update(keyset) return kwargs def __call__(self, state): ''' Call support. :param args: :param kwargs: :return: ''' ret = { 'name': state.pop('name'), 'changes': {}, 'result': True, 'comment': '', } out = {} functions = ['Functions:'] try: for ref_func, ref_kwargs in state.items(): if ref_func not in self.EXPORTED: raise salt.exceptions.SaltInvocationError('Function {} is not found'.format(ref_func)) out[ref_func] = getattr(self, ref_func)(**self.get_kwargs(ref_kwargs)) functions.append(' - {}'.format(ref_func)) ret['comment'] = '\n'.join(functions) except Exception as ex: ret['comment'] = str(ex) ret['result'] = False ret['changes'] = out return ret def collected(self, group, filename=None, host=None, location=None, move=True, all=True): ''' Sync archives to a central place. :param name: :param group: :param filename: :param host: :param location: :param move: :param all: :return: ''' ret = { 'name': 'support.collected', 'changes': {}, 'result': True, 'comment': '', } location = location or tempfile.gettempdir() self.check_destination(location, group) ret['changes'] = __salt__['support.sync'](group, name=filename, host=host, location=location, move=move, all=all) return ret def taken(self, profile='default', pillar=None, archive=None, output='nested'): ''' Takes minion support config data. :param profile: :param pillar: :param archive: :param output: :return: ''' ret = { 'name': 'support.taken', 'changes': {}, 'result': True, } result = __salt__['support.run'](profile=profile, pillar=pillar, archive=archive, output=output) if result.get('archive'): ret['comment'] = 'Information about this system has been saved to {} file.'.format(result['archive']) ret['changes']['archive'] = result['archive'] ret['changes']['messages'] = {} for key in ['info', 'error', 'warning']: if result.get('messages', {}).get(key): ret['changes']['messages'][key] = result['messages'][key] else: ret['comment'] = '' return ret
saltstack/salt
salt/states/saltsupport.py
SaltSupportState.collected
python
def collected(self, group, filename=None, host=None, location=None, move=True, all=True): ''' Sync archives to a central place. :param name: :param group: :param filename: :param host: :param location: :param move: :param all: :return: ''' ret = { 'name': 'support.collected', 'changes': {}, 'result': True, 'comment': '', } location = location or tempfile.gettempdir() self.check_destination(location, group) ret['changes'] = __salt__['support.sync'](group, name=filename, host=host, location=location, move=move, all=all) return ret
Sync archives to a central place. :param name: :param group: :param filename: :param host: :param location: :param move: :param all: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltsupport.py#L115-L139
[ "def check_destination(self, location, group):\n '''\n Check destination for the archives.\n :return:\n '''\n # Pre-create destination, since rsync will\n # put one file named as group\n try:\n destination = os.path.join(location, group)\n if os.path.exists(destination) and not os.path.isdir(destination):\n raise salt.exceptions.SaltException('Destination \"{}\" should be directory!'.format(destination))\n if not os.path.exists(destination):\n os.makedirs(destination)\n log.debug('Created destination directory for archives: %s', destination)\n else:\n log.debug('Archives destination directory %s already exists', destination)\n except OSError as err:\n log.error(err)\n" ]
class SaltSupportState(object): ''' Salt-support. ''' EXPORTED = ['collected', 'taken'] def get_kwargs(self, data): kwargs = {} for keyset in data: kwargs.update(keyset) return kwargs def __call__(self, state): ''' Call support. :param args: :param kwargs: :return: ''' ret = { 'name': state.pop('name'), 'changes': {}, 'result': True, 'comment': '', } out = {} functions = ['Functions:'] try: for ref_func, ref_kwargs in state.items(): if ref_func not in self.EXPORTED: raise salt.exceptions.SaltInvocationError('Function {} is not found'.format(ref_func)) out[ref_func] = getattr(self, ref_func)(**self.get_kwargs(ref_kwargs)) functions.append(' - {}'.format(ref_func)) ret['comment'] = '\n'.join(functions) except Exception as ex: ret['comment'] = str(ex) ret['result'] = False ret['changes'] = out return ret def check_destination(self, location, group): ''' Check destination for the archives. :return: ''' # Pre-create destination, since rsync will # put one file named as group try: destination = os.path.join(location, group) if os.path.exists(destination) and not os.path.isdir(destination): raise salt.exceptions.SaltException('Destination "{}" should be directory!'.format(destination)) if not os.path.exists(destination): os.makedirs(destination) log.debug('Created destination directory for archives: %s', destination) else: log.debug('Archives destination directory %s already exists', destination) except OSError as err: log.error(err) def taken(self, profile='default', pillar=None, archive=None, output='nested'): ''' Takes minion support config data. :param profile: :param pillar: :param archive: :param output: :return: ''' ret = { 'name': 'support.taken', 'changes': {}, 'result': True, } result = __salt__['support.run'](profile=profile, pillar=pillar, archive=archive, output=output) if result.get('archive'): ret['comment'] = 'Information about this system has been saved to {} file.'.format(result['archive']) ret['changes']['archive'] = result['archive'] ret['changes']['messages'] = {} for key in ['info', 'error', 'warning']: if result.get('messages', {}).get(key): ret['changes']['messages'][key] = result['messages'][key] else: ret['comment'] = '' return ret
saltstack/salt
salt/states/saltsupport.py
SaltSupportState.taken
python
def taken(self, profile='default', pillar=None, archive=None, output='nested'): ''' Takes minion support config data. :param profile: :param pillar: :param archive: :param output: :return: ''' ret = { 'name': 'support.taken', 'changes': {}, 'result': True, } result = __salt__['support.run'](profile=profile, pillar=pillar, archive=archive, output=output) if result.get('archive'): ret['comment'] = 'Information about this system has been saved to {} file.'.format(result['archive']) ret['changes']['archive'] = result['archive'] ret['changes']['messages'] = {} for key in ['info', 'error', 'warning']: if result.get('messages', {}).get(key): ret['changes']['messages'][key] = result['messages'][key] else: ret['comment'] = '' return ret
Takes minion support config data. :param profile: :param pillar: :param archive: :param output: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltsupport.py#L141-L168
null
class SaltSupportState(object): ''' Salt-support. ''' EXPORTED = ['collected', 'taken'] def get_kwargs(self, data): kwargs = {} for keyset in data: kwargs.update(keyset) return kwargs def __call__(self, state): ''' Call support. :param args: :param kwargs: :return: ''' ret = { 'name': state.pop('name'), 'changes': {}, 'result': True, 'comment': '', } out = {} functions = ['Functions:'] try: for ref_func, ref_kwargs in state.items(): if ref_func not in self.EXPORTED: raise salt.exceptions.SaltInvocationError('Function {} is not found'.format(ref_func)) out[ref_func] = getattr(self, ref_func)(**self.get_kwargs(ref_kwargs)) functions.append(' - {}'.format(ref_func)) ret['comment'] = '\n'.join(functions) except Exception as ex: ret['comment'] = str(ex) ret['result'] = False ret['changes'] = out return ret def check_destination(self, location, group): ''' Check destination for the archives. :return: ''' # Pre-create destination, since rsync will # put one file named as group try: destination = os.path.join(location, group) if os.path.exists(destination) and not os.path.isdir(destination): raise salt.exceptions.SaltException('Destination "{}" should be directory!'.format(destination)) if not os.path.exists(destination): os.makedirs(destination) log.debug('Created destination directory for archives: %s', destination) else: log.debug('Archives destination directory %s already exists', destination) except OSError as err: log.error(err) def collected(self, group, filename=None, host=None, location=None, move=True, all=True): ''' Sync archives to a central place. :param name: :param group: :param filename: :param host: :param location: :param move: :param all: :return: ''' ret = { 'name': 'support.collected', 'changes': {}, 'result': True, 'comment': '', } location = location or tempfile.gettempdir() self.check_destination(location, group) ret['changes'] = __salt__['support.sync'](group, name=filename, host=host, location=location, move=move, all=all) return ret
saltstack/salt
salt/modules/vmctl.py
create_disk
python
def create_disk(name, size): ''' Create a VMM disk with the specified `name` and `size`. size: Size in megabytes, or use a specifier such as M, G, T. CLI Example: .. code-block:: bash salt '*' vmctl.create_disk /path/to/disk.img size=10G ''' ret = False cmd = 'vmctl create {0} -s {1}'.format(name, size) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered creating disk image', info={'errors': [result['stderr']], 'changes': ret} ) return ret
Create a VMM disk with the specified `name` and `size`. size: Size in megabytes, or use a specifier such as M, G, T. CLI Example: .. code-block:: bash salt '*' vmctl.create_disk /path/to/disk.img size=10G
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vmctl.py#L50-L78
null
# -*- coding: utf-8 -*- ''' Manage vms running on the OpenBSD VMM hypervisor using vmctl(8). .. versionadded:: 2019.2.0 :codeauthor: ``Jasper Lievisse Adriaanse <jasper@openbsd.org>`` .. note:: This module requires the `vmd` service to be running on the OpenBSD target machine. ''' from __future__ import absolute_import # Import python libs import logging import re # Imoprt salt libs: import salt.utils.path from salt.exceptions import (CommandExecutionError, SaltInvocationError) from salt.ext.six.moves import zip log = logging.getLogger(__name__) def __virtual__(): ''' Only works on OpenBSD with vmctl(8) present. ''' if __grains__['os'] == 'OpenBSD' and salt.utils.path.which('vmctl'): return True return (False, 'The vmm execution module cannot be loaded: either the system is not OpenBSD or the vmctl binary was not found') def _id_to_name(id): ''' Lookup the name associated with a VM id. ''' vm = status(id=id) if vm == {}: return None else: return vm['name'] def load(path): ''' Load additional configuration from the specified file. path Path to the configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.load path=/etc/vm.switches.conf ''' ret = False cmd = 'vmctl load {0}'.format(path) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reload(): ''' Remove all stopped VMs and reload configuration from the default configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.reload ''' ret = False cmd = 'vmctl reload' result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reset(all=False, vms=False, switches=False): ''' Reset the running state of VMM or a subsystem. all: Reset the running state. switches: Reset the configured switches. vms: Reset and terminate all VMs. CLI Example: .. code-block:: bash salt '*' vmctl.reset all=True ''' ret = False cmd = ['vmctl', 'reset'] if all: cmd.append('all') elif vms: cmd.append('vms') elif switches: cmd.append('switches') result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def start(name=None, id=None, bootpath=None, disk=None, disks=None, local_iface=False, memory=None, nics=0, switch=None): ''' Starts a VM defined by the specified parameters. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. bootpath: Path to a kernel or BIOS image to load. disk: Path to a single disk to use. disks: List of multiple disks to use. local_iface: Whether to add a local network interface. See "LOCAL INTERFACES" in the vmctl(8) manual page for more information. memory: Memory size of the VM specified in megabytes. switch: Add a network interface that is attached to the specified virtual switch on the host. CLI Example: .. code-block:: bash salt '*' vmctl.start 2 # start VM with id 2 salt '*' vmctl.start name=web1 bootpath='/bsd.rd' nics=2 memory=512M disk='/disk.img' ''' ret = {'changes': False, 'console': None} cmd = ['vmctl', 'start'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) name = _id_to_name(id) if nics > 0: cmd.append('-i {0}'.format(nics)) # Paths cannot be appended as otherwise the inserted whitespace is treated by # vmctl as being part of the path. if bootpath: cmd.extend(['-b', bootpath]) if memory: cmd.append('-m {0}'.format(memory)) if switch: cmd.append('-n {0}'.format(switch)) if local_iface: cmd.append('-L') if disk and disks: raise SaltInvocationError('Must provide either "disks" or "disk"') if disk: cmd.extend(['-d', disk]) if disks: cmd.extend(['-d', x] for x in disks) # Before attempting to define a new VM, make sure it doesn't already exist. # Otherwise return to indicate nothing was changed. if len(cmd) > 3: vmstate = status(name) if vmstate: ret['comment'] = 'VM already exists and cannot be redefined' return ret result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret['changes'] = True m = re.match(r'.*successfully, tty (\/dev.*)', result['stderr']) if m: ret['console'] = m.groups()[0] else: m = re.match(r'.*Operation already in progress$', result['stderr']) if m: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def status(name=None, id=None): ''' List VMs running on the host, or only the VM specified by ``id``. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.status # to list all VMs salt '*' vmctl.status name=web1 # to get a single VM ''' ret = {} cmd = ['vmctl', 'status'] result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Problem encountered running vmctl', info={'error': [result['stderr']], 'changes': ret} ) # Grab the header and save it with the lowercase names. header = result['stdout'].splitlines()[0].split() header = list([x.lower() for x in header]) # A VM can be in one of the following states (from vmm.c:vcpu_state_decode()) # - stopped # - running # - requesting termination # - terminated # - unknown for line in result['stdout'].splitlines()[1:]: data = line.split() vm = dict(list(zip(header, data))) vmname = vm.pop('name') if vm['pid'] == '-': # If the VM has no PID it's not running. vm['state'] = 'stopped' elif vmname and data[-2] == '-': # When a VM does have a PID and the second to last field is a '-', it's # transitioning to another state. A VM name itself cannot contain a # '-' so it's safe to split on '-'. vm['state'] = data[-1] else: vm['state'] = 'running' # When the status is requested of a single VM (by name) which is stopping, # vmctl doesn't print the status line. So we'll parse the full list and # return when we've found the requested VM. if id and int(vm['id']) == id: return {vmname: vm} elif name and vmname == name: return {vmname: vm} else: ret[vmname] = vm # Assert we've not come this far when an id or name have been provided. That # means the requested VM does not exist. if id or name: return {} return ret def stop(name=None, id=None): ''' Stop (terminate) the VM identified by the given id or name. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.stop name=alpine ''' ret = {} cmd = ['vmctl', 'stop'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: if re.match('^vmctl: sent request to terminate vm.*', result['stderr']): ret['changes'] = True else: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
saltstack/salt
salt/modules/vmctl.py
load
python
def load(path): ''' Load additional configuration from the specified file. path Path to the configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.load path=/etc/vm.switches.conf ''' ret = False cmd = 'vmctl load {0}'.format(path) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
Load additional configuration from the specified file. path Path to the configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.load path=/etc/vm.switches.conf
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vmctl.py#L81-L107
null
# -*- coding: utf-8 -*- ''' Manage vms running on the OpenBSD VMM hypervisor using vmctl(8). .. versionadded:: 2019.2.0 :codeauthor: ``Jasper Lievisse Adriaanse <jasper@openbsd.org>`` .. note:: This module requires the `vmd` service to be running on the OpenBSD target machine. ''' from __future__ import absolute_import # Import python libs import logging import re # Imoprt salt libs: import salt.utils.path from salt.exceptions import (CommandExecutionError, SaltInvocationError) from salt.ext.six.moves import zip log = logging.getLogger(__name__) def __virtual__(): ''' Only works on OpenBSD with vmctl(8) present. ''' if __grains__['os'] == 'OpenBSD' and salt.utils.path.which('vmctl'): return True return (False, 'The vmm execution module cannot be loaded: either the system is not OpenBSD or the vmctl binary was not found') def _id_to_name(id): ''' Lookup the name associated with a VM id. ''' vm = status(id=id) if vm == {}: return None else: return vm['name'] def create_disk(name, size): ''' Create a VMM disk with the specified `name` and `size`. size: Size in megabytes, or use a specifier such as M, G, T. CLI Example: .. code-block:: bash salt '*' vmctl.create_disk /path/to/disk.img size=10G ''' ret = False cmd = 'vmctl create {0} -s {1}'.format(name, size) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered creating disk image', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reload(): ''' Remove all stopped VMs and reload configuration from the default configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.reload ''' ret = False cmd = 'vmctl reload' result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reset(all=False, vms=False, switches=False): ''' Reset the running state of VMM or a subsystem. all: Reset the running state. switches: Reset the configured switches. vms: Reset and terminate all VMs. CLI Example: .. code-block:: bash salt '*' vmctl.reset all=True ''' ret = False cmd = ['vmctl', 'reset'] if all: cmd.append('all') elif vms: cmd.append('vms') elif switches: cmd.append('switches') result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def start(name=None, id=None, bootpath=None, disk=None, disks=None, local_iface=False, memory=None, nics=0, switch=None): ''' Starts a VM defined by the specified parameters. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. bootpath: Path to a kernel or BIOS image to load. disk: Path to a single disk to use. disks: List of multiple disks to use. local_iface: Whether to add a local network interface. See "LOCAL INTERFACES" in the vmctl(8) manual page for more information. memory: Memory size of the VM specified in megabytes. switch: Add a network interface that is attached to the specified virtual switch on the host. CLI Example: .. code-block:: bash salt '*' vmctl.start 2 # start VM with id 2 salt '*' vmctl.start name=web1 bootpath='/bsd.rd' nics=2 memory=512M disk='/disk.img' ''' ret = {'changes': False, 'console': None} cmd = ['vmctl', 'start'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) name = _id_to_name(id) if nics > 0: cmd.append('-i {0}'.format(nics)) # Paths cannot be appended as otherwise the inserted whitespace is treated by # vmctl as being part of the path. if bootpath: cmd.extend(['-b', bootpath]) if memory: cmd.append('-m {0}'.format(memory)) if switch: cmd.append('-n {0}'.format(switch)) if local_iface: cmd.append('-L') if disk and disks: raise SaltInvocationError('Must provide either "disks" or "disk"') if disk: cmd.extend(['-d', disk]) if disks: cmd.extend(['-d', x] for x in disks) # Before attempting to define a new VM, make sure it doesn't already exist. # Otherwise return to indicate nothing was changed. if len(cmd) > 3: vmstate = status(name) if vmstate: ret['comment'] = 'VM already exists and cannot be redefined' return ret result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret['changes'] = True m = re.match(r'.*successfully, tty (\/dev.*)', result['stderr']) if m: ret['console'] = m.groups()[0] else: m = re.match(r'.*Operation already in progress$', result['stderr']) if m: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def status(name=None, id=None): ''' List VMs running on the host, or only the VM specified by ``id``. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.status # to list all VMs salt '*' vmctl.status name=web1 # to get a single VM ''' ret = {} cmd = ['vmctl', 'status'] result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Problem encountered running vmctl', info={'error': [result['stderr']], 'changes': ret} ) # Grab the header and save it with the lowercase names. header = result['stdout'].splitlines()[0].split() header = list([x.lower() for x in header]) # A VM can be in one of the following states (from vmm.c:vcpu_state_decode()) # - stopped # - running # - requesting termination # - terminated # - unknown for line in result['stdout'].splitlines()[1:]: data = line.split() vm = dict(list(zip(header, data))) vmname = vm.pop('name') if vm['pid'] == '-': # If the VM has no PID it's not running. vm['state'] = 'stopped' elif vmname and data[-2] == '-': # When a VM does have a PID and the second to last field is a '-', it's # transitioning to another state. A VM name itself cannot contain a # '-' so it's safe to split on '-'. vm['state'] = data[-1] else: vm['state'] = 'running' # When the status is requested of a single VM (by name) which is stopping, # vmctl doesn't print the status line. So we'll parse the full list and # return when we've found the requested VM. if id and int(vm['id']) == id: return {vmname: vm} elif name and vmname == name: return {vmname: vm} else: ret[vmname] = vm # Assert we've not come this far when an id or name have been provided. That # means the requested VM does not exist. if id or name: return {} return ret def stop(name=None, id=None): ''' Stop (terminate) the VM identified by the given id or name. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.stop name=alpine ''' ret = {} cmd = ['vmctl', 'stop'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: if re.match('^vmctl: sent request to terminate vm.*', result['stderr']): ret['changes'] = True else: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
saltstack/salt
salt/modules/vmctl.py
reload
python
def reload(): ''' Remove all stopped VMs and reload configuration from the default configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.reload ''' ret = False cmd = 'vmctl reload' result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
Remove all stopped VMs and reload configuration from the default configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.reload
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vmctl.py#L110-L133
null
# -*- coding: utf-8 -*- ''' Manage vms running on the OpenBSD VMM hypervisor using vmctl(8). .. versionadded:: 2019.2.0 :codeauthor: ``Jasper Lievisse Adriaanse <jasper@openbsd.org>`` .. note:: This module requires the `vmd` service to be running on the OpenBSD target machine. ''' from __future__ import absolute_import # Import python libs import logging import re # Imoprt salt libs: import salt.utils.path from salt.exceptions import (CommandExecutionError, SaltInvocationError) from salt.ext.six.moves import zip log = logging.getLogger(__name__) def __virtual__(): ''' Only works on OpenBSD with vmctl(8) present. ''' if __grains__['os'] == 'OpenBSD' and salt.utils.path.which('vmctl'): return True return (False, 'The vmm execution module cannot be loaded: either the system is not OpenBSD or the vmctl binary was not found') def _id_to_name(id): ''' Lookup the name associated with a VM id. ''' vm = status(id=id) if vm == {}: return None else: return vm['name'] def create_disk(name, size): ''' Create a VMM disk with the specified `name` and `size`. size: Size in megabytes, or use a specifier such as M, G, T. CLI Example: .. code-block:: bash salt '*' vmctl.create_disk /path/to/disk.img size=10G ''' ret = False cmd = 'vmctl create {0} -s {1}'.format(name, size) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered creating disk image', info={'errors': [result['stderr']], 'changes': ret} ) return ret def load(path): ''' Load additional configuration from the specified file. path Path to the configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.load path=/etc/vm.switches.conf ''' ret = False cmd = 'vmctl load {0}'.format(path) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reset(all=False, vms=False, switches=False): ''' Reset the running state of VMM or a subsystem. all: Reset the running state. switches: Reset the configured switches. vms: Reset and terminate all VMs. CLI Example: .. code-block:: bash salt '*' vmctl.reset all=True ''' ret = False cmd = ['vmctl', 'reset'] if all: cmd.append('all') elif vms: cmd.append('vms') elif switches: cmd.append('switches') result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def start(name=None, id=None, bootpath=None, disk=None, disks=None, local_iface=False, memory=None, nics=0, switch=None): ''' Starts a VM defined by the specified parameters. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. bootpath: Path to a kernel or BIOS image to load. disk: Path to a single disk to use. disks: List of multiple disks to use. local_iface: Whether to add a local network interface. See "LOCAL INTERFACES" in the vmctl(8) manual page for more information. memory: Memory size of the VM specified in megabytes. switch: Add a network interface that is attached to the specified virtual switch on the host. CLI Example: .. code-block:: bash salt '*' vmctl.start 2 # start VM with id 2 salt '*' vmctl.start name=web1 bootpath='/bsd.rd' nics=2 memory=512M disk='/disk.img' ''' ret = {'changes': False, 'console': None} cmd = ['vmctl', 'start'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) name = _id_to_name(id) if nics > 0: cmd.append('-i {0}'.format(nics)) # Paths cannot be appended as otherwise the inserted whitespace is treated by # vmctl as being part of the path. if bootpath: cmd.extend(['-b', bootpath]) if memory: cmd.append('-m {0}'.format(memory)) if switch: cmd.append('-n {0}'.format(switch)) if local_iface: cmd.append('-L') if disk and disks: raise SaltInvocationError('Must provide either "disks" or "disk"') if disk: cmd.extend(['-d', disk]) if disks: cmd.extend(['-d', x] for x in disks) # Before attempting to define a new VM, make sure it doesn't already exist. # Otherwise return to indicate nothing was changed. if len(cmd) > 3: vmstate = status(name) if vmstate: ret['comment'] = 'VM already exists and cannot be redefined' return ret result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret['changes'] = True m = re.match(r'.*successfully, tty (\/dev.*)', result['stderr']) if m: ret['console'] = m.groups()[0] else: m = re.match(r'.*Operation already in progress$', result['stderr']) if m: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def status(name=None, id=None): ''' List VMs running on the host, or only the VM specified by ``id``. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.status # to list all VMs salt '*' vmctl.status name=web1 # to get a single VM ''' ret = {} cmd = ['vmctl', 'status'] result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Problem encountered running vmctl', info={'error': [result['stderr']], 'changes': ret} ) # Grab the header and save it with the lowercase names. header = result['stdout'].splitlines()[0].split() header = list([x.lower() for x in header]) # A VM can be in one of the following states (from vmm.c:vcpu_state_decode()) # - stopped # - running # - requesting termination # - terminated # - unknown for line in result['stdout'].splitlines()[1:]: data = line.split() vm = dict(list(zip(header, data))) vmname = vm.pop('name') if vm['pid'] == '-': # If the VM has no PID it's not running. vm['state'] = 'stopped' elif vmname and data[-2] == '-': # When a VM does have a PID and the second to last field is a '-', it's # transitioning to another state. A VM name itself cannot contain a # '-' so it's safe to split on '-'. vm['state'] = data[-1] else: vm['state'] = 'running' # When the status is requested of a single VM (by name) which is stopping, # vmctl doesn't print the status line. So we'll parse the full list and # return when we've found the requested VM. if id and int(vm['id']) == id: return {vmname: vm} elif name and vmname == name: return {vmname: vm} else: ret[vmname] = vm # Assert we've not come this far when an id or name have been provided. That # means the requested VM does not exist. if id or name: return {} return ret def stop(name=None, id=None): ''' Stop (terminate) the VM identified by the given id or name. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.stop name=alpine ''' ret = {} cmd = ['vmctl', 'stop'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: if re.match('^vmctl: sent request to terminate vm.*', result['stderr']): ret['changes'] = True else: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
saltstack/salt
salt/modules/vmctl.py
reset
python
def reset(all=False, vms=False, switches=False): ''' Reset the running state of VMM or a subsystem. all: Reset the running state. switches: Reset the configured switches. vms: Reset and terminate all VMs. CLI Example: .. code-block:: bash salt '*' vmctl.reset all=True ''' ret = False cmd = ['vmctl', 'reset'] if all: cmd.append('all') elif vms: cmd.append('vms') elif switches: cmd.append('switches') result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
Reset the running state of VMM or a subsystem. all: Reset the running state. switches: Reset the configured switches. vms: Reset and terminate all VMs. CLI Example: .. code-block:: bash salt '*' vmctl.reset all=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vmctl.py#L136-L177
null
# -*- coding: utf-8 -*- ''' Manage vms running on the OpenBSD VMM hypervisor using vmctl(8). .. versionadded:: 2019.2.0 :codeauthor: ``Jasper Lievisse Adriaanse <jasper@openbsd.org>`` .. note:: This module requires the `vmd` service to be running on the OpenBSD target machine. ''' from __future__ import absolute_import # Import python libs import logging import re # Imoprt salt libs: import salt.utils.path from salt.exceptions import (CommandExecutionError, SaltInvocationError) from salt.ext.six.moves import zip log = logging.getLogger(__name__) def __virtual__(): ''' Only works on OpenBSD with vmctl(8) present. ''' if __grains__['os'] == 'OpenBSD' and salt.utils.path.which('vmctl'): return True return (False, 'The vmm execution module cannot be loaded: either the system is not OpenBSD or the vmctl binary was not found') def _id_to_name(id): ''' Lookup the name associated with a VM id. ''' vm = status(id=id) if vm == {}: return None else: return vm['name'] def create_disk(name, size): ''' Create a VMM disk with the specified `name` and `size`. size: Size in megabytes, or use a specifier such as M, G, T. CLI Example: .. code-block:: bash salt '*' vmctl.create_disk /path/to/disk.img size=10G ''' ret = False cmd = 'vmctl create {0} -s {1}'.format(name, size) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered creating disk image', info={'errors': [result['stderr']], 'changes': ret} ) return ret def load(path): ''' Load additional configuration from the specified file. path Path to the configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.load path=/etc/vm.switches.conf ''' ret = False cmd = 'vmctl load {0}'.format(path) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reload(): ''' Remove all stopped VMs and reload configuration from the default configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.reload ''' ret = False cmd = 'vmctl reload' result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def start(name=None, id=None, bootpath=None, disk=None, disks=None, local_iface=False, memory=None, nics=0, switch=None): ''' Starts a VM defined by the specified parameters. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. bootpath: Path to a kernel or BIOS image to load. disk: Path to a single disk to use. disks: List of multiple disks to use. local_iface: Whether to add a local network interface. See "LOCAL INTERFACES" in the vmctl(8) manual page for more information. memory: Memory size of the VM specified in megabytes. switch: Add a network interface that is attached to the specified virtual switch on the host. CLI Example: .. code-block:: bash salt '*' vmctl.start 2 # start VM with id 2 salt '*' vmctl.start name=web1 bootpath='/bsd.rd' nics=2 memory=512M disk='/disk.img' ''' ret = {'changes': False, 'console': None} cmd = ['vmctl', 'start'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) name = _id_to_name(id) if nics > 0: cmd.append('-i {0}'.format(nics)) # Paths cannot be appended as otherwise the inserted whitespace is treated by # vmctl as being part of the path. if bootpath: cmd.extend(['-b', bootpath]) if memory: cmd.append('-m {0}'.format(memory)) if switch: cmd.append('-n {0}'.format(switch)) if local_iface: cmd.append('-L') if disk and disks: raise SaltInvocationError('Must provide either "disks" or "disk"') if disk: cmd.extend(['-d', disk]) if disks: cmd.extend(['-d', x] for x in disks) # Before attempting to define a new VM, make sure it doesn't already exist. # Otherwise return to indicate nothing was changed. if len(cmd) > 3: vmstate = status(name) if vmstate: ret['comment'] = 'VM already exists and cannot be redefined' return ret result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret['changes'] = True m = re.match(r'.*successfully, tty (\/dev.*)', result['stderr']) if m: ret['console'] = m.groups()[0] else: m = re.match(r'.*Operation already in progress$', result['stderr']) if m: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def status(name=None, id=None): ''' List VMs running on the host, or only the VM specified by ``id``. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.status # to list all VMs salt '*' vmctl.status name=web1 # to get a single VM ''' ret = {} cmd = ['vmctl', 'status'] result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Problem encountered running vmctl', info={'error': [result['stderr']], 'changes': ret} ) # Grab the header and save it with the lowercase names. header = result['stdout'].splitlines()[0].split() header = list([x.lower() for x in header]) # A VM can be in one of the following states (from vmm.c:vcpu_state_decode()) # - stopped # - running # - requesting termination # - terminated # - unknown for line in result['stdout'].splitlines()[1:]: data = line.split() vm = dict(list(zip(header, data))) vmname = vm.pop('name') if vm['pid'] == '-': # If the VM has no PID it's not running. vm['state'] = 'stopped' elif vmname and data[-2] == '-': # When a VM does have a PID and the second to last field is a '-', it's # transitioning to another state. A VM name itself cannot contain a # '-' so it's safe to split on '-'. vm['state'] = data[-1] else: vm['state'] = 'running' # When the status is requested of a single VM (by name) which is stopping, # vmctl doesn't print the status line. So we'll parse the full list and # return when we've found the requested VM. if id and int(vm['id']) == id: return {vmname: vm} elif name and vmname == name: return {vmname: vm} else: ret[vmname] = vm # Assert we've not come this far when an id or name have been provided. That # means the requested VM does not exist. if id or name: return {} return ret def stop(name=None, id=None): ''' Stop (terminate) the VM identified by the given id or name. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.stop name=alpine ''' ret = {} cmd = ['vmctl', 'stop'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: if re.match('^vmctl: sent request to terminate vm.*', result['stderr']): ret['changes'] = True else: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
saltstack/salt
salt/modules/vmctl.py
start
python
def start(name=None, id=None, bootpath=None, disk=None, disks=None, local_iface=False, memory=None, nics=0, switch=None): ''' Starts a VM defined by the specified parameters. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. bootpath: Path to a kernel or BIOS image to load. disk: Path to a single disk to use. disks: List of multiple disks to use. local_iface: Whether to add a local network interface. See "LOCAL INTERFACES" in the vmctl(8) manual page for more information. memory: Memory size of the VM specified in megabytes. switch: Add a network interface that is attached to the specified virtual switch on the host. CLI Example: .. code-block:: bash salt '*' vmctl.start 2 # start VM with id 2 salt '*' vmctl.start name=web1 bootpath='/bsd.rd' nics=2 memory=512M disk='/disk.img' ''' ret = {'changes': False, 'console': None} cmd = ['vmctl', 'start'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) name = _id_to_name(id) if nics > 0: cmd.append('-i {0}'.format(nics)) # Paths cannot be appended as otherwise the inserted whitespace is treated by # vmctl as being part of the path. if bootpath: cmd.extend(['-b', bootpath]) if memory: cmd.append('-m {0}'.format(memory)) if switch: cmd.append('-n {0}'.format(switch)) if local_iface: cmd.append('-L') if disk and disks: raise SaltInvocationError('Must provide either "disks" or "disk"') if disk: cmd.extend(['-d', disk]) if disks: cmd.extend(['-d', x] for x in disks) # Before attempting to define a new VM, make sure it doesn't already exist. # Otherwise return to indicate nothing was changed. if len(cmd) > 3: vmstate = status(name) if vmstate: ret['comment'] = 'VM already exists and cannot be redefined' return ret result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret['changes'] = True m = re.match(r'.*successfully, tty (\/dev.*)', result['stderr']) if m: ret['console'] = m.groups()[0] else: m = re.match(r'.*Operation already in progress$', result['stderr']) if m: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
Starts a VM defined by the specified parameters. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. bootpath: Path to a kernel or BIOS image to load. disk: Path to a single disk to use. disks: List of multiple disks to use. local_iface: Whether to add a local network interface. See "LOCAL INTERFACES" in the vmctl(8) manual page for more information. memory: Memory size of the VM specified in megabytes. switch: Add a network interface that is attached to the specified virtual switch on the host. CLI Example: .. code-block:: bash salt '*' vmctl.start 2 # start VM with id 2 salt '*' vmctl.start name=web1 bootpath='/bsd.rd' nics=2 memory=512M disk='/disk.img'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vmctl.py#L180-L283
[ "def status(name=None, id=None):\n '''\n List VMs running on the host, or only the VM specified by ``id``. When\n both a name and id are provided, the id is ignored.\n\n name:\n Name of the defined VM.\n\n id:\n VM id.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' vmctl.status # to list all VMs\n salt '*' vmctl.status name=web1 # to get a single VM\n '''\n ret = {}\n cmd = ['vmctl', 'status']\n\n result = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False)\n\n if result['retcode'] != 0:\n raise CommandExecutionError(\n 'Problem encountered running vmctl',\n info={'error': [result['stderr']], 'changes': ret}\n )\n\n # Grab the header and save it with the lowercase names.\n header = result['stdout'].splitlines()[0].split()\n header = list([x.lower() for x in header])\n\n # A VM can be in one of the following states (from vmm.c:vcpu_state_decode())\n # - stopped\n # - running\n # - requesting termination\n # - terminated\n # - unknown\n\n for line in result['stdout'].splitlines()[1:]:\n data = line.split()\n vm = dict(list(zip(header, data)))\n vmname = vm.pop('name')\n if vm['pid'] == '-':\n # If the VM has no PID it's not running.\n vm['state'] = 'stopped'\n elif vmname and data[-2] == '-':\n # When a VM does have a PID and the second to last field is a '-', it's\n # transitioning to another state. A VM name itself cannot contain a\n # '-' so it's safe to split on '-'.\n vm['state'] = data[-1]\n else:\n vm['state'] = 'running'\n\n # When the status is requested of a single VM (by name) which is stopping,\n # vmctl doesn't print the status line. So we'll parse the full list and\n # return when we've found the requested VM.\n if id and int(vm['id']) == id:\n return {vmname: vm}\n elif name and vmname == name:\n return {vmname: vm}\n else:\n ret[vmname] = vm\n\n # Assert we've not come this far when an id or name have been provided. That\n # means the requested VM does not exist.\n if id or name:\n return {}\n\n return ret\n", "def _id_to_name(id):\n '''\n Lookup the name associated with a VM id.\n '''\n vm = status(id=id)\n if vm == {}:\n return None\n else:\n return vm['name']\n" ]
# -*- coding: utf-8 -*- ''' Manage vms running on the OpenBSD VMM hypervisor using vmctl(8). .. versionadded:: 2019.2.0 :codeauthor: ``Jasper Lievisse Adriaanse <jasper@openbsd.org>`` .. note:: This module requires the `vmd` service to be running on the OpenBSD target machine. ''' from __future__ import absolute_import # Import python libs import logging import re # Imoprt salt libs: import salt.utils.path from salt.exceptions import (CommandExecutionError, SaltInvocationError) from salt.ext.six.moves import zip log = logging.getLogger(__name__) def __virtual__(): ''' Only works on OpenBSD with vmctl(8) present. ''' if __grains__['os'] == 'OpenBSD' and salt.utils.path.which('vmctl'): return True return (False, 'The vmm execution module cannot be loaded: either the system is not OpenBSD or the vmctl binary was not found') def _id_to_name(id): ''' Lookup the name associated with a VM id. ''' vm = status(id=id) if vm == {}: return None else: return vm['name'] def create_disk(name, size): ''' Create a VMM disk with the specified `name` and `size`. size: Size in megabytes, or use a specifier such as M, G, T. CLI Example: .. code-block:: bash salt '*' vmctl.create_disk /path/to/disk.img size=10G ''' ret = False cmd = 'vmctl create {0} -s {1}'.format(name, size) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered creating disk image', info={'errors': [result['stderr']], 'changes': ret} ) return ret def load(path): ''' Load additional configuration from the specified file. path Path to the configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.load path=/etc/vm.switches.conf ''' ret = False cmd = 'vmctl load {0}'.format(path) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reload(): ''' Remove all stopped VMs and reload configuration from the default configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.reload ''' ret = False cmd = 'vmctl reload' result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reset(all=False, vms=False, switches=False): ''' Reset the running state of VMM or a subsystem. all: Reset the running state. switches: Reset the configured switches. vms: Reset and terminate all VMs. CLI Example: .. code-block:: bash salt '*' vmctl.reset all=True ''' ret = False cmd = ['vmctl', 'reset'] if all: cmd.append('all') elif vms: cmd.append('vms') elif switches: cmd.append('switches') result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def status(name=None, id=None): ''' List VMs running on the host, or only the VM specified by ``id``. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.status # to list all VMs salt '*' vmctl.status name=web1 # to get a single VM ''' ret = {} cmd = ['vmctl', 'status'] result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Problem encountered running vmctl', info={'error': [result['stderr']], 'changes': ret} ) # Grab the header and save it with the lowercase names. header = result['stdout'].splitlines()[0].split() header = list([x.lower() for x in header]) # A VM can be in one of the following states (from vmm.c:vcpu_state_decode()) # - stopped # - running # - requesting termination # - terminated # - unknown for line in result['stdout'].splitlines()[1:]: data = line.split() vm = dict(list(zip(header, data))) vmname = vm.pop('name') if vm['pid'] == '-': # If the VM has no PID it's not running. vm['state'] = 'stopped' elif vmname and data[-2] == '-': # When a VM does have a PID and the second to last field is a '-', it's # transitioning to another state. A VM name itself cannot contain a # '-' so it's safe to split on '-'. vm['state'] = data[-1] else: vm['state'] = 'running' # When the status is requested of a single VM (by name) which is stopping, # vmctl doesn't print the status line. So we'll parse the full list and # return when we've found the requested VM. if id and int(vm['id']) == id: return {vmname: vm} elif name and vmname == name: return {vmname: vm} else: ret[vmname] = vm # Assert we've not come this far when an id or name have been provided. That # means the requested VM does not exist. if id or name: return {} return ret def stop(name=None, id=None): ''' Stop (terminate) the VM identified by the given id or name. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.stop name=alpine ''' ret = {} cmd = ['vmctl', 'stop'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: if re.match('^vmctl: sent request to terminate vm.*', result['stderr']): ret['changes'] = True else: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
saltstack/salt
salt/modules/vmctl.py
status
python
def status(name=None, id=None): ''' List VMs running on the host, or only the VM specified by ``id``. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.status # to list all VMs salt '*' vmctl.status name=web1 # to get a single VM ''' ret = {} cmd = ['vmctl', 'status'] result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Problem encountered running vmctl', info={'error': [result['stderr']], 'changes': ret} ) # Grab the header and save it with the lowercase names. header = result['stdout'].splitlines()[0].split() header = list([x.lower() for x in header]) # A VM can be in one of the following states (from vmm.c:vcpu_state_decode()) # - stopped # - running # - requesting termination # - terminated # - unknown for line in result['stdout'].splitlines()[1:]: data = line.split() vm = dict(list(zip(header, data))) vmname = vm.pop('name') if vm['pid'] == '-': # If the VM has no PID it's not running. vm['state'] = 'stopped' elif vmname and data[-2] == '-': # When a VM does have a PID and the second to last field is a '-', it's # transitioning to another state. A VM name itself cannot contain a # '-' so it's safe to split on '-'. vm['state'] = data[-1] else: vm['state'] = 'running' # When the status is requested of a single VM (by name) which is stopping, # vmctl doesn't print the status line. So we'll parse the full list and # return when we've found the requested VM. if id and int(vm['id']) == id: return {vmname: vm} elif name and vmname == name: return {vmname: vm} else: ret[vmname] = vm # Assert we've not come this far when an id or name have been provided. That # means the requested VM does not exist. if id or name: return {} return ret
List VMs running on the host, or only the VM specified by ``id``. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.status # to list all VMs salt '*' vmctl.status name=web1 # to get a single VM
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vmctl.py#L286-L358
null
# -*- coding: utf-8 -*- ''' Manage vms running on the OpenBSD VMM hypervisor using vmctl(8). .. versionadded:: 2019.2.0 :codeauthor: ``Jasper Lievisse Adriaanse <jasper@openbsd.org>`` .. note:: This module requires the `vmd` service to be running on the OpenBSD target machine. ''' from __future__ import absolute_import # Import python libs import logging import re # Imoprt salt libs: import salt.utils.path from salt.exceptions import (CommandExecutionError, SaltInvocationError) from salt.ext.six.moves import zip log = logging.getLogger(__name__) def __virtual__(): ''' Only works on OpenBSD with vmctl(8) present. ''' if __grains__['os'] == 'OpenBSD' and salt.utils.path.which('vmctl'): return True return (False, 'The vmm execution module cannot be loaded: either the system is not OpenBSD or the vmctl binary was not found') def _id_to_name(id): ''' Lookup the name associated with a VM id. ''' vm = status(id=id) if vm == {}: return None else: return vm['name'] def create_disk(name, size): ''' Create a VMM disk with the specified `name` and `size`. size: Size in megabytes, or use a specifier such as M, G, T. CLI Example: .. code-block:: bash salt '*' vmctl.create_disk /path/to/disk.img size=10G ''' ret = False cmd = 'vmctl create {0} -s {1}'.format(name, size) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered creating disk image', info={'errors': [result['stderr']], 'changes': ret} ) return ret def load(path): ''' Load additional configuration from the specified file. path Path to the configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.load path=/etc/vm.switches.conf ''' ret = False cmd = 'vmctl load {0}'.format(path) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reload(): ''' Remove all stopped VMs and reload configuration from the default configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.reload ''' ret = False cmd = 'vmctl reload' result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reset(all=False, vms=False, switches=False): ''' Reset the running state of VMM or a subsystem. all: Reset the running state. switches: Reset the configured switches. vms: Reset and terminate all VMs. CLI Example: .. code-block:: bash salt '*' vmctl.reset all=True ''' ret = False cmd = ['vmctl', 'reset'] if all: cmd.append('all') elif vms: cmd.append('vms') elif switches: cmd.append('switches') result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def start(name=None, id=None, bootpath=None, disk=None, disks=None, local_iface=False, memory=None, nics=0, switch=None): ''' Starts a VM defined by the specified parameters. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. bootpath: Path to a kernel or BIOS image to load. disk: Path to a single disk to use. disks: List of multiple disks to use. local_iface: Whether to add a local network interface. See "LOCAL INTERFACES" in the vmctl(8) manual page for more information. memory: Memory size of the VM specified in megabytes. switch: Add a network interface that is attached to the specified virtual switch on the host. CLI Example: .. code-block:: bash salt '*' vmctl.start 2 # start VM with id 2 salt '*' vmctl.start name=web1 bootpath='/bsd.rd' nics=2 memory=512M disk='/disk.img' ''' ret = {'changes': False, 'console': None} cmd = ['vmctl', 'start'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) name = _id_to_name(id) if nics > 0: cmd.append('-i {0}'.format(nics)) # Paths cannot be appended as otherwise the inserted whitespace is treated by # vmctl as being part of the path. if bootpath: cmd.extend(['-b', bootpath]) if memory: cmd.append('-m {0}'.format(memory)) if switch: cmd.append('-n {0}'.format(switch)) if local_iface: cmd.append('-L') if disk and disks: raise SaltInvocationError('Must provide either "disks" or "disk"') if disk: cmd.extend(['-d', disk]) if disks: cmd.extend(['-d', x] for x in disks) # Before attempting to define a new VM, make sure it doesn't already exist. # Otherwise return to indicate nothing was changed. if len(cmd) > 3: vmstate = status(name) if vmstate: ret['comment'] = 'VM already exists and cannot be redefined' return ret result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret['changes'] = True m = re.match(r'.*successfully, tty (\/dev.*)', result['stderr']) if m: ret['console'] = m.groups()[0] else: m = re.match(r'.*Operation already in progress$', result['stderr']) if m: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def stop(name=None, id=None): ''' Stop (terminate) the VM identified by the given id or name. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.stop name=alpine ''' ret = {} cmd = ['vmctl', 'stop'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: if re.match('^vmctl: sent request to terminate vm.*', result['stderr']): ret['changes'] = True else: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
saltstack/salt
salt/modules/vmctl.py
stop
python
def stop(name=None, id=None): ''' Stop (terminate) the VM identified by the given id or name. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.stop name=alpine ''' ret = {} cmd = ['vmctl', 'stop'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: if re.match('^vmctl: sent request to terminate vm.*', result['stderr']): ret['changes'] = True else: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret
Stop (terminate) the VM identified by the given id or name. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.stop name=alpine
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vmctl.py#L361-L403
null
# -*- coding: utf-8 -*- ''' Manage vms running on the OpenBSD VMM hypervisor using vmctl(8). .. versionadded:: 2019.2.0 :codeauthor: ``Jasper Lievisse Adriaanse <jasper@openbsd.org>`` .. note:: This module requires the `vmd` service to be running on the OpenBSD target machine. ''' from __future__ import absolute_import # Import python libs import logging import re # Imoprt salt libs: import salt.utils.path from salt.exceptions import (CommandExecutionError, SaltInvocationError) from salt.ext.six.moves import zip log = logging.getLogger(__name__) def __virtual__(): ''' Only works on OpenBSD with vmctl(8) present. ''' if __grains__['os'] == 'OpenBSD' and salt.utils.path.which('vmctl'): return True return (False, 'The vmm execution module cannot be loaded: either the system is not OpenBSD or the vmctl binary was not found') def _id_to_name(id): ''' Lookup the name associated with a VM id. ''' vm = status(id=id) if vm == {}: return None else: return vm['name'] def create_disk(name, size): ''' Create a VMM disk with the specified `name` and `size`. size: Size in megabytes, or use a specifier such as M, G, T. CLI Example: .. code-block:: bash salt '*' vmctl.create_disk /path/to/disk.img size=10G ''' ret = False cmd = 'vmctl create {0} -s {1}'.format(name, size) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered creating disk image', info={'errors': [result['stderr']], 'changes': ret} ) return ret def load(path): ''' Load additional configuration from the specified file. path Path to the configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.load path=/etc/vm.switches.conf ''' ret = False cmd = 'vmctl load {0}'.format(path) result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reload(): ''' Remove all stopped VMs and reload configuration from the default configuration file. CLI Example: .. code-block:: bash salt '*' vmctl.reload ''' ret = False cmd = 'vmctl reload' result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def reset(all=False, vms=False, switches=False): ''' Reset the running state of VMM or a subsystem. all: Reset the running state. switches: Reset the configured switches. vms: Reset and terminate all VMs. CLI Example: .. code-block:: bash salt '*' vmctl.reset all=True ''' ret = False cmd = ['vmctl', 'reset'] if all: cmd.append('all') elif vms: cmd.append('vms') elif switches: cmd.append('switches') result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret = True else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def start(name=None, id=None, bootpath=None, disk=None, disks=None, local_iface=False, memory=None, nics=0, switch=None): ''' Starts a VM defined by the specified parameters. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. bootpath: Path to a kernel or BIOS image to load. disk: Path to a single disk to use. disks: List of multiple disks to use. local_iface: Whether to add a local network interface. See "LOCAL INTERFACES" in the vmctl(8) manual page for more information. memory: Memory size of the VM specified in megabytes. switch: Add a network interface that is attached to the specified virtual switch on the host. CLI Example: .. code-block:: bash salt '*' vmctl.start 2 # start VM with id 2 salt '*' vmctl.start name=web1 bootpath='/bsd.rd' nics=2 memory=512M disk='/disk.img' ''' ret = {'changes': False, 'console': None} cmd = ['vmctl', 'start'] if not (name or id): raise SaltInvocationError('Must provide either "name" or "id"') elif name: cmd.append(name) else: cmd.append(id) name = _id_to_name(id) if nics > 0: cmd.append('-i {0}'.format(nics)) # Paths cannot be appended as otherwise the inserted whitespace is treated by # vmctl as being part of the path. if bootpath: cmd.extend(['-b', bootpath]) if memory: cmd.append('-m {0}'.format(memory)) if switch: cmd.append('-n {0}'.format(switch)) if local_iface: cmd.append('-L') if disk and disks: raise SaltInvocationError('Must provide either "disks" or "disk"') if disk: cmd.extend(['-d', disk]) if disks: cmd.extend(['-d', x] for x in disks) # Before attempting to define a new VM, make sure it doesn't already exist. # Otherwise return to indicate nothing was changed. if len(cmd) > 3: vmstate = status(name) if vmstate: ret['comment'] = 'VM already exists and cannot be redefined' return ret result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] == 0: ret['changes'] = True m = re.match(r'.*successfully, tty (\/dev.*)', result['stderr']) if m: ret['console'] = m.groups()[0] else: m = re.match(r'.*Operation already in progress$', result['stderr']) if m: ret['changes'] = False else: raise CommandExecutionError( 'Problem encountered running vmctl', info={'errors': [result['stderr']], 'changes': ret} ) return ret def status(name=None, id=None): ''' List VMs running on the host, or only the VM specified by ``id``. When both a name and id are provided, the id is ignored. name: Name of the defined VM. id: VM id. CLI Example: .. code-block:: bash salt '*' vmctl.status # to list all VMs salt '*' vmctl.status name=web1 # to get a single VM ''' ret = {} cmd = ['vmctl', 'status'] result = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Problem encountered running vmctl', info={'error': [result['stderr']], 'changes': ret} ) # Grab the header and save it with the lowercase names. header = result['stdout'].splitlines()[0].split() header = list([x.lower() for x in header]) # A VM can be in one of the following states (from vmm.c:vcpu_state_decode()) # - stopped # - running # - requesting termination # - terminated # - unknown for line in result['stdout'].splitlines()[1:]: data = line.split() vm = dict(list(zip(header, data))) vmname = vm.pop('name') if vm['pid'] == '-': # If the VM has no PID it's not running. vm['state'] = 'stopped' elif vmname and data[-2] == '-': # When a VM does have a PID and the second to last field is a '-', it's # transitioning to another state. A VM name itself cannot contain a # '-' so it's safe to split on '-'. vm['state'] = data[-1] else: vm['state'] = 'running' # When the status is requested of a single VM (by name) which is stopping, # vmctl doesn't print the status line. So we'll parse the full list and # return when we've found the requested VM. if id and int(vm['id']) == id: return {vmname: vm} elif name and vmname == name: return {vmname: vm} else: ret[vmname] = vm # Assert we've not come this far when an id or name have been provided. That # means the requested VM does not exist. if id or name: return {} return ret
saltstack/salt
salt/modules/munin.py
run
python
def run(plugins): ''' Run one or more named munin plugins CLI Example: .. code-block:: bash salt '*' munin.run uptime salt '*' munin.run uptime,cpu,load,memory ''' all_plugins = list_plugins() if isinstance(plugins, six.string_types): plugins = plugins.split(',') data = {} for plugin in plugins: if plugin not in all_plugins: continue data[plugin] = {} muninout = __salt__['cmd.run']( 'munin-run {0}'.format(plugin), python_shell=False) for line in muninout.split('\n'): if 'value' in line: # This skips multigraph lines, etc key, val = line.split(' ') key = key.split('.')[0] try: # We only want numbers if '.' in val: val = float(val) else: val = int(val) data[plugin][key] = val except ValueError: pass return data
Run one or more named munin plugins CLI Example: .. code-block:: bash salt '*' munin.run uptime salt '*' munin.run uptime,cpu,load,memory
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/munin.py#L33-L70
[ "def list_plugins():\n '''\n List all the munin plugins\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' munin.list_plugins\n '''\n pluginlist = os.listdir(PLUGINDIR)\n ret = []\n for plugin in pluginlist:\n # Check if execute bit\n statf = os.path.join(PLUGINDIR, plugin)\n try:\n executebit = stat.S_IXUSR & os.stat(statf)[stat.ST_MODE]\n except OSError:\n pass\n if executebit:\n ret.append(plugin)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Run munin plugins/checks from salt and format the output as data. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import stat # Import salt libs from salt.ext import six import salt.utils.files import salt.utils.stringutils PLUGINDIR = '/etc/munin/plugins/' def __virtual__(): ''' Only load the module if munin-node is installed ''' if os.path.exists('/etc/munin/munin-node.conf'): return 'munin' return (False, 'The munin execution module cannot be loaded: munin-node is not installed.') def _get_conf(fname='/etc/munin/munin-node.cfg'): with salt.utils.files.fopen(fname, 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()) def run_all(): ''' Run all the munin plugins CLI Example: .. code-block:: bash salt '*' munin.run_all ''' plugins = list_plugins() ret = {} for plugin in plugins: ret.update(run(plugin)) return ret def list_plugins(): ''' List all the munin plugins CLI Example: .. code-block:: bash salt '*' munin.list_plugins ''' pluginlist = os.listdir(PLUGINDIR) ret = [] for plugin in pluginlist: # Check if execute bit statf = os.path.join(PLUGINDIR, plugin) try: executebit = stat.S_IXUSR & os.stat(statf)[stat.ST_MODE] except OSError: pass if executebit: ret.append(plugin) return ret
saltstack/salt
salt/modules/munin.py
run_all
python
def run_all(): ''' Run all the munin plugins CLI Example: .. code-block:: bash salt '*' munin.run_all ''' plugins = list_plugins() ret = {} for plugin in plugins: ret.update(run(plugin)) return ret
Run all the munin plugins CLI Example: .. code-block:: bash salt '*' munin.run_all
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/munin.py#L73-L87
[ "def run(plugins):\n '''\n Run one or more named munin plugins\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' munin.run uptime\n salt '*' munin.run uptime,cpu,load,memory\n '''\n all_plugins = list_plugins()\n\n if isinstance(plugins, six.string_types):\n plugins = plugins.split(',')\n\n data = {}\n for plugin in plugins:\n if plugin not in all_plugins:\n continue\n data[plugin] = {}\n muninout = __salt__['cmd.run'](\n 'munin-run {0}'.format(plugin),\n python_shell=False)\n for line in muninout.split('\\n'):\n if 'value' in line: # This skips multigraph lines, etc\n key, val = line.split(' ')\n key = key.split('.')[0]\n try:\n # We only want numbers\n if '.' in val:\n val = float(val)\n else:\n val = int(val)\n data[plugin][key] = val\n except ValueError:\n pass\n return data\n", "def list_plugins():\n '''\n List all the munin plugins\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' munin.list_plugins\n '''\n pluginlist = os.listdir(PLUGINDIR)\n ret = []\n for plugin in pluginlist:\n # Check if execute bit\n statf = os.path.join(PLUGINDIR, plugin)\n try:\n executebit = stat.S_IXUSR & os.stat(statf)[stat.ST_MODE]\n except OSError:\n pass\n if executebit:\n ret.append(plugin)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Run munin plugins/checks from salt and format the output as data. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import stat # Import salt libs from salt.ext import six import salt.utils.files import salt.utils.stringutils PLUGINDIR = '/etc/munin/plugins/' def __virtual__(): ''' Only load the module if munin-node is installed ''' if os.path.exists('/etc/munin/munin-node.conf'): return 'munin' return (False, 'The munin execution module cannot be loaded: munin-node is not installed.') def _get_conf(fname='/etc/munin/munin-node.cfg'): with salt.utils.files.fopen(fname, 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()) def run(plugins): ''' Run one or more named munin plugins CLI Example: .. code-block:: bash salt '*' munin.run uptime salt '*' munin.run uptime,cpu,load,memory ''' all_plugins = list_plugins() if isinstance(plugins, six.string_types): plugins = plugins.split(',') data = {} for plugin in plugins: if plugin not in all_plugins: continue data[plugin] = {} muninout = __salt__['cmd.run']( 'munin-run {0}'.format(plugin), python_shell=False) for line in muninout.split('\n'): if 'value' in line: # This skips multigraph lines, etc key, val = line.split(' ') key = key.split('.')[0] try: # We only want numbers if '.' in val: val = float(val) else: val = int(val) data[plugin][key] = val except ValueError: pass return data def list_plugins(): ''' List all the munin plugins CLI Example: .. code-block:: bash salt '*' munin.list_plugins ''' pluginlist = os.listdir(PLUGINDIR) ret = [] for plugin in pluginlist: # Check if execute bit statf = os.path.join(PLUGINDIR, plugin) try: executebit = stat.S_IXUSR & os.stat(statf)[stat.ST_MODE] except OSError: pass if executebit: ret.append(plugin) return ret
saltstack/salt
salt/modules/munin.py
list_plugins
python
def list_plugins(): ''' List all the munin plugins CLI Example: .. code-block:: bash salt '*' munin.list_plugins ''' pluginlist = os.listdir(PLUGINDIR) ret = [] for plugin in pluginlist: # Check if execute bit statf = os.path.join(PLUGINDIR, plugin) try: executebit = stat.S_IXUSR & os.stat(statf)[stat.ST_MODE] except OSError: pass if executebit: ret.append(plugin) return ret
List all the munin plugins CLI Example: .. code-block:: bash salt '*' munin.list_plugins
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/munin.py#L90-L111
null
# -*- coding: utf-8 -*- ''' Run munin plugins/checks from salt and format the output as data. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import stat # Import salt libs from salt.ext import six import salt.utils.files import salt.utils.stringutils PLUGINDIR = '/etc/munin/plugins/' def __virtual__(): ''' Only load the module if munin-node is installed ''' if os.path.exists('/etc/munin/munin-node.conf'): return 'munin' return (False, 'The munin execution module cannot be loaded: munin-node is not installed.') def _get_conf(fname='/etc/munin/munin-node.cfg'): with salt.utils.files.fopen(fname, 'r') as fp_: return salt.utils.stringutils.to_unicode(fp_.read()) def run(plugins): ''' Run one or more named munin plugins CLI Example: .. code-block:: bash salt '*' munin.run uptime salt '*' munin.run uptime,cpu,load,memory ''' all_plugins = list_plugins() if isinstance(plugins, six.string_types): plugins = plugins.split(',') data = {} for plugin in plugins: if plugin not in all_plugins: continue data[plugin] = {} muninout = __salt__['cmd.run']( 'munin-run {0}'.format(plugin), python_shell=False) for line in muninout.split('\n'): if 'value' in line: # This skips multigraph lines, etc key, val = line.split(' ') key = key.split('.')[0] try: # We only want numbers if '.' in val: val = float(val) else: val = int(val) data[plugin][key] = val except ValueError: pass return data def run_all(): ''' Run all the munin plugins CLI Example: .. code-block:: bash salt '*' munin.run_all ''' plugins = list_plugins() ret = {} for plugin in plugins: ret.update(run(plugin)) return ret
saltstack/salt
salt/modules/kernelpkg_linux_yum.py
list_installed
python
def list_installed(): ''' Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed ''' result = __salt__['pkg.version'](_package_name(), versions_as_list=True) if result is None: return [] if six.PY2: return sorted(result, cmp=_cmp_version) else: return sorted(result, key=functools.cmp_to_key(_cmp_version))
Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kernelpkg_linux_yum.py#L64-L81
[ "def _package_name():\n '''\n Return static string for the package name\n '''\n return 'kernel'\n" ]
# -*- coding: utf-8 -*- ''' Manage Linux kernel packages on YUM-based systems ''' from __future__ import absolute_import, print_function, unicode_literals import functools import logging try: # Import Salt libs from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion from salt.exceptions import CommandExecutionError import salt.utils.data import salt.utils.functools import salt.utils.systemd import salt.modules.yumpkg __IMPORT_ERROR = None except ImportError as exc: __IMPORT_ERROR = exc.__str__() log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'kernelpkg' # Import functions from yumpkg _yum = salt.utils.functools.namespaced_function(salt.modules.yumpkg._yum, globals()) # pylint: disable=invalid-name, protected-access def __virtual__(): ''' Load this module on RedHat-based systems only ''' if __IMPORT_ERROR: return (False, __IMPORT_ERROR) if __grains__.get('os_family', '') == 'RedHat': return __virtualname__ elif __grains__.get('os', '').lower() \ in ('amazon', 'xcp', 'xenserver', 'virtuozzolinux'): return __virtualname__ return (False, "Module kernelpkg_linux_yum: no YUM based system detected") def active(): ''' Return the version of the running kernel. CLI Example: .. code-block:: bash salt '*' kernelpkg.active ''' if 'pkg.normalize_name' in __salt__: return __salt__['pkg.normalize_name'](__grains__['kernelrelease']) return __grains__['kernelrelease'] def latest_available(): ''' Return the version of the latest kernel from the package repositories. CLI Example: .. code-block:: bash salt '*' kernelpkg.latest_available ''' result = __salt__['pkg.latest_version'](_package_name()) if result == '': result = latest_installed() return result def latest_installed(): ''' Return the version of the latest installed kernel. CLI Example: .. code-block:: bash salt '*' kernelpkg.latest_installed .. note:: This function may not return the same value as :py:func:`~salt.modules.kernelpkg_linux_yum.active` if a new kernel has been installed and the system has not yet been rebooted. The :py:func:`~salt.modules.kernelpkg_linux_yum.needs_reboot` function exists to detect this condition. ''' pkgs = list_installed() if pkgs: return pkgs[-1] return None def needs_reboot(): ''' Detect if a new kernel version has been installed but is not running. Returns True if a new kernel is installed, False otherwise. CLI Example: .. code-block:: bash salt '*' kernelpkg.needs_reboot ''' return _LooseVersion(active()) < _LooseVersion(latest_installed()) 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 :py:func:`~salt.modules.system.reboot` for more details on this argument. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade salt '*' kernelpkg.upgrade reboot=True at_time=1 .. note:: An immediate reboot often shuts down the system before the minion has a chance to return, resulting in errors. A minimal delay (1 minute) is useful to ensure the result is delivered to the master. ''' result = __salt__['pkg.upgrade'](name=_package_name()) _needs_reboot = needs_reboot() ret = { 'upgrades': result, 'active': active(), 'latest_installed': latest_installed(), 'reboot_requested': reboot, 'reboot_required': _needs_reboot } if reboot and _needs_reboot: log.warning('Rebooting system due to kernel upgrade') __salt__['system.reboot'](at_time=at_time) return ret def upgrade_available(): ''' Detect if a new kernel version is available in the repositories. Returns True if a new kernel is available, False otherwise. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade_available ''' return _LooseVersion(latest_available()) > _LooseVersion(latest_installed()) 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_yum.list_installed`, not the package name. CLI Example: .. code-block:: bash salt '*' kernelpkg.remove 3.10.0-327.el7 ''' if release not in list_installed(): raise CommandExecutionError('Kernel release \'{0}\' is not installed'.format(release)) if release == active(): raise CommandExecutionError('Active kernel cannot be removed') target = '{0}-{1}'.format(_package_name(), release) log.info('Removing kernel package %s', target) old = __salt__['pkg.list_pkgs']() # Build the command string cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend([_yum(), '-y', 'remove', target]) # Execute the command out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) # Look for the changes in installed packages __context__.pop('pkg.list_pkgs', None) new = __salt__['pkg.list_pkgs']() ret = salt.utils.data.compare_dicts(old, new) # Look for command execution errors if out['retcode'] != 0: raise CommandExecutionError( 'Error occurred removing package(s)', info={'errors': [out['stderr']], 'changes': ret} ) return {'removed': [target]} 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 packages other than the active one will be removed. CLI Example: .. code-block:: bash salt '*' kernelpkg.cleanup ''' removed = [] # Loop over all installed kernel packages for kernel in list_installed(): # Keep the active kernel package if kernel == active(): continue # Optionally keep the latest kernel package if keep_latest and kernel == latest_installed(): continue # Remove the kernel package removed.extend(remove(kernel)['removed']) return {'removed': removed} def _package_name(): ''' Return static string for the package name ''' return 'kernel' 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
saltstack/salt
salt/modules/kernelpkg_linux_yum.py
upgrade
python
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 :py:func:`~salt.modules.system.reboot` for more details on this argument. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade salt '*' kernelpkg.upgrade reboot=True at_time=1 .. note:: An immediate reboot often shuts down the system before the minion has a chance to return, resulting in errors. A minimal delay (1 minute) is useful to ensure the result is delivered to the master. ''' result = __salt__['pkg.upgrade'](name=_package_name()) _needs_reboot = needs_reboot() ret = { 'upgrades': result, 'active': active(), 'latest_installed': latest_installed(), 'reboot_requested': reboot, 'reboot_required': _needs_reboot } if reboot and _needs_reboot: log.warning('Rebooting system due to kernel upgrade') __salt__['system.reboot'](at_time=at_time) return ret
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 more details on this argument. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade salt '*' kernelpkg.upgrade reboot=True at_time=1 .. note:: An immediate reboot often shuts down the system before the minion has a chance to return, resulting in errors. A minimal delay (1 minute) is useful to ensure the result is delivered to the master.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kernelpkg_linux_yum.py#L138-L178
[ "def active():\n '''\n Return the version of the running kernel.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' kernelpkg.active\n '''\n if 'pkg.normalize_name' in __salt__:\n return __salt__['pkg.normalize_name'](__grains__['kernelrelease'])\n\n return __grains__['kernelrelease']\n", "def latest_installed():\n '''\n Return the version of the latest installed kernel.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' kernelpkg.latest_installed\n\n .. note::\n This function may not return the same value as\n :py:func:`~salt.modules.kernelpkg_linux_yum.active` if a new kernel\n has been installed and the system has not yet been rebooted.\n The :py:func:`~salt.modules.kernelpkg_linux_yum.needs_reboot` function\n exists to detect this condition.\n '''\n pkgs = list_installed()\n if pkgs:\n return pkgs[-1]\n\n return None\n", "def needs_reboot():\n '''\n Detect if a new kernel version has been installed but is not running.\n Returns True if a new kernel is installed, False otherwise.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' kernelpkg.needs_reboot\n '''\n return _LooseVersion(active()) < _LooseVersion(latest_installed())\n", "def _package_name():\n '''\n Return static string for the package name\n '''\n return 'kernel'\n" ]
# -*- coding: utf-8 -*- ''' Manage Linux kernel packages on YUM-based systems ''' from __future__ import absolute_import, print_function, unicode_literals import functools import logging try: # Import Salt libs from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion from salt.exceptions import CommandExecutionError import salt.utils.data import salt.utils.functools import salt.utils.systemd import salt.modules.yumpkg __IMPORT_ERROR = None except ImportError as exc: __IMPORT_ERROR = exc.__str__() log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'kernelpkg' # Import functions from yumpkg _yum = salt.utils.functools.namespaced_function(salt.modules.yumpkg._yum, globals()) # pylint: disable=invalid-name, protected-access def __virtual__(): ''' Load this module on RedHat-based systems only ''' if __IMPORT_ERROR: return (False, __IMPORT_ERROR) if __grains__.get('os_family', '') == 'RedHat': return __virtualname__ elif __grains__.get('os', '').lower() \ in ('amazon', 'xcp', 'xenserver', 'virtuozzolinux'): return __virtualname__ return (False, "Module kernelpkg_linux_yum: no YUM based system detected") def active(): ''' Return the version of the running kernel. CLI Example: .. code-block:: bash salt '*' kernelpkg.active ''' if 'pkg.normalize_name' in __salt__: return __salt__['pkg.normalize_name'](__grains__['kernelrelease']) return __grains__['kernelrelease'] def list_installed(): ''' Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed ''' result = __salt__['pkg.version'](_package_name(), versions_as_list=True) if result is None: return [] if six.PY2: return sorted(result, cmp=_cmp_version) else: return sorted(result, key=functools.cmp_to_key(_cmp_version)) def latest_available(): ''' Return the version of the latest kernel from the package repositories. CLI Example: .. code-block:: bash salt '*' kernelpkg.latest_available ''' result = __salt__['pkg.latest_version'](_package_name()) if result == '': result = latest_installed() return result def latest_installed(): ''' Return the version of the latest installed kernel. CLI Example: .. code-block:: bash salt '*' kernelpkg.latest_installed .. note:: This function may not return the same value as :py:func:`~salt.modules.kernelpkg_linux_yum.active` if a new kernel has been installed and the system has not yet been rebooted. The :py:func:`~salt.modules.kernelpkg_linux_yum.needs_reboot` function exists to detect this condition. ''' pkgs = list_installed() if pkgs: return pkgs[-1] return None def needs_reboot(): ''' Detect if a new kernel version has been installed but is not running. Returns True if a new kernel is installed, False otherwise. CLI Example: .. code-block:: bash salt '*' kernelpkg.needs_reboot ''' return _LooseVersion(active()) < _LooseVersion(latest_installed()) def upgrade_available(): ''' Detect if a new kernel version is available in the repositories. Returns True if a new kernel is available, False otherwise. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade_available ''' return _LooseVersion(latest_available()) > _LooseVersion(latest_installed()) 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_yum.list_installed`, not the package name. CLI Example: .. code-block:: bash salt '*' kernelpkg.remove 3.10.0-327.el7 ''' if release not in list_installed(): raise CommandExecutionError('Kernel release \'{0}\' is not installed'.format(release)) if release == active(): raise CommandExecutionError('Active kernel cannot be removed') target = '{0}-{1}'.format(_package_name(), release) log.info('Removing kernel package %s', target) old = __salt__['pkg.list_pkgs']() # Build the command string cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend([_yum(), '-y', 'remove', target]) # Execute the command out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) # Look for the changes in installed packages __context__.pop('pkg.list_pkgs', None) new = __salt__['pkg.list_pkgs']() ret = salt.utils.data.compare_dicts(old, new) # Look for command execution errors if out['retcode'] != 0: raise CommandExecutionError( 'Error occurred removing package(s)', info={'errors': [out['stderr']], 'changes': ret} ) return {'removed': [target]} 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 packages other than the active one will be removed. CLI Example: .. code-block:: bash salt '*' kernelpkg.cleanup ''' removed = [] # Loop over all installed kernel packages for kernel in list_installed(): # Keep the active kernel package if kernel == active(): continue # Optionally keep the latest kernel package if keep_latest and kernel == latest_installed(): continue # Remove the kernel package removed.extend(remove(kernel)['removed']) return {'removed': removed} def _package_name(): ''' Return static string for the package name ''' return 'kernel' 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
saltstack/salt
salt/modules/kernelpkg_linux_yum.py
remove
python
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_yum.list_installed`, not the package name. CLI Example: .. code-block:: bash salt '*' kernelpkg.remove 3.10.0-327.el7 ''' if release not in list_installed(): raise CommandExecutionError('Kernel release \'{0}\' is not installed'.format(release)) if release == active(): raise CommandExecutionError('Active kernel cannot be removed') target = '{0}-{1}'.format(_package_name(), release) log.info('Removing kernel package %s', target) old = __salt__['pkg.list_pkgs']() # Build the command string cmd = [] if salt.utils.systemd.has_scope(__context__) \ and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend([_yum(), '-y', 'remove', target]) # Execute the command out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) # Look for the changes in installed packages __context__.pop('pkg.list_pkgs', None) new = __salt__['pkg.list_pkgs']() ret = salt.utils.data.compare_dicts(old, new) # Look for command execution errors if out['retcode'] != 0: raise CommandExecutionError( 'Error occurred removing package(s)', info={'errors': [out['stderr']], 'changes': ret} ) return {'removed': [target]}
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_yum.list_installed`, not the package name. CLI Example: .. code-block:: bash salt '*' kernelpkg.remove 3.10.0-327.el7
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kernelpkg_linux_yum.py#L195-L246
[ "def active():\n '''\n Return the version of the running kernel.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' kernelpkg.active\n '''\n if 'pkg.normalize_name' in __salt__:\n return __salt__['pkg.normalize_name'](__grains__['kernelrelease'])\n\n return __grains__['kernelrelease']\n", "def has_scope(context=None):\n '''\n Scopes were introduced in systemd 205, this function returns a boolean\n which is true when the minion is systemd-booted and running systemd>=205.\n '''\n if not booted(context):\n return False\n _sd_version = version(context)\n if _sd_version is None:\n return False\n return _sd_version >= 205\n", "def list_installed():\n '''\n Return a list of all installed kernels.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' kernelpkg.list_installed\n '''\n result = __salt__['pkg.version'](_package_name(), versions_as_list=True)\n if result is None:\n return []\n\n if six.PY2:\n return sorted(result, cmp=_cmp_version)\n else:\n return sorted(result, key=functools.cmp_to_key(_cmp_version))\n", "def _package_name():\n '''\n Return static string for the package name\n '''\n return 'kernel'\n" ]
# -*- coding: utf-8 -*- ''' Manage Linux kernel packages on YUM-based systems ''' from __future__ import absolute_import, print_function, unicode_literals import functools import logging try: # Import Salt libs from salt.ext import six from salt.utils.versions import LooseVersion as _LooseVersion from salt.exceptions import CommandExecutionError import salt.utils.data import salt.utils.functools import salt.utils.systemd import salt.modules.yumpkg __IMPORT_ERROR = None except ImportError as exc: __IMPORT_ERROR = exc.__str__() log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'kernelpkg' # Import functions from yumpkg _yum = salt.utils.functools.namespaced_function(salt.modules.yumpkg._yum, globals()) # pylint: disable=invalid-name, protected-access def __virtual__(): ''' Load this module on RedHat-based systems only ''' if __IMPORT_ERROR: return (False, __IMPORT_ERROR) if __grains__.get('os_family', '') == 'RedHat': return __virtualname__ elif __grains__.get('os', '').lower() \ in ('amazon', 'xcp', 'xenserver', 'virtuozzolinux'): return __virtualname__ return (False, "Module kernelpkg_linux_yum: no YUM based system detected") def active(): ''' Return the version of the running kernel. CLI Example: .. code-block:: bash salt '*' kernelpkg.active ''' if 'pkg.normalize_name' in __salt__: return __salt__['pkg.normalize_name'](__grains__['kernelrelease']) return __grains__['kernelrelease'] def list_installed(): ''' Return a list of all installed kernels. CLI Example: .. code-block:: bash salt '*' kernelpkg.list_installed ''' result = __salt__['pkg.version'](_package_name(), versions_as_list=True) if result is None: return [] if six.PY2: return sorted(result, cmp=_cmp_version) else: return sorted(result, key=functools.cmp_to_key(_cmp_version)) def latest_available(): ''' Return the version of the latest kernel from the package repositories. CLI Example: .. code-block:: bash salt '*' kernelpkg.latest_available ''' result = __salt__['pkg.latest_version'](_package_name()) if result == '': result = latest_installed() return result def latest_installed(): ''' Return the version of the latest installed kernel. CLI Example: .. code-block:: bash salt '*' kernelpkg.latest_installed .. note:: This function may not return the same value as :py:func:`~salt.modules.kernelpkg_linux_yum.active` if a new kernel has been installed and the system has not yet been rebooted. The :py:func:`~salt.modules.kernelpkg_linux_yum.needs_reboot` function exists to detect this condition. ''' pkgs = list_installed() if pkgs: return pkgs[-1] return None def needs_reboot(): ''' Detect if a new kernel version has been installed but is not running. Returns True if a new kernel is installed, False otherwise. CLI Example: .. code-block:: bash salt '*' kernelpkg.needs_reboot ''' return _LooseVersion(active()) < _LooseVersion(latest_installed()) 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 :py:func:`~salt.modules.system.reboot` for more details on this argument. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade salt '*' kernelpkg.upgrade reboot=True at_time=1 .. note:: An immediate reboot often shuts down the system before the minion has a chance to return, resulting in errors. A minimal delay (1 minute) is useful to ensure the result is delivered to the master. ''' result = __salt__['pkg.upgrade'](name=_package_name()) _needs_reboot = needs_reboot() ret = { 'upgrades': result, 'active': active(), 'latest_installed': latest_installed(), 'reboot_requested': reboot, 'reboot_required': _needs_reboot } if reboot and _needs_reboot: log.warning('Rebooting system due to kernel upgrade') __salt__['system.reboot'](at_time=at_time) return ret def upgrade_available(): ''' Detect if a new kernel version is available in the repositories. Returns True if a new kernel is available, False otherwise. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade_available ''' return _LooseVersion(latest_available()) > _LooseVersion(latest_installed()) 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 packages other than the active one will be removed. CLI Example: .. code-block:: bash salt '*' kernelpkg.cleanup ''' removed = [] # Loop over all installed kernel packages for kernel in list_installed(): # Keep the active kernel package if kernel == active(): continue # Optionally keep the latest kernel package if keep_latest and kernel == latest_installed(): continue # Remove the kernel package removed.extend(remove(kernel)['removed']) return {'removed': removed} def _package_name(): ''' Return static string for the package name ''' return 'kernel' 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
saltstack/salt
salt/utils/cache.py
context_cache
python
def context_cache(func): ''' A decorator to be used module functions which need to cache their context. To evaluate a __context__ and re-hydrate it if a given key is empty or contains no items, pass a list of keys to evaulate. ''' def context_cache_wrap(*args, **kwargs): func_context = func.__globals__['__context__'] func_opts = func.__globals__['__opts__'] func_name = func.__globals__['__name__'] context_cache = ContextCache(func_opts, func_name) if not func_context and os.path.isfile(context_cache.cache_path): salt.utils.dictupdate.update(func_context, context_cache.get_cache_context()) else: context_cache.cache_context(func_context) return func(*args, **kwargs) return context_cache_wrap
A decorator to be used module functions which need to cache their context. To evaluate a __context__ and re-hydrate it if a given key is empty or contains no items, pass a list of keys to evaulate.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L344-L363
null
# -*- coding: utf-8 -*- ''' In-memory caching used by Salt ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import time import logging try: import salt.utils.msgpack as msgpack except ImportError: msgpack = None # Import salt libs import salt.config import salt.payload import salt.utils.data import salt.utils.dictupdate import salt.utils.files # Import third party libs from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin from salt.utils.zeromq import zmq log = logging.getLogger(__name__) class CacheFactory(object): ''' Cache which can use a number of backends ''' @classmethod def factory(cls, backend, ttl, *args, **kwargs): log.info('Factory backend: %s', backend) if backend == 'memory': return CacheDict(ttl, *args, **kwargs) elif backend == 'disk': return CacheDisk(ttl, kwargs['minion_cache_path'], *args, **kwargs) else: log.error('CacheFactory received unrecognized cache type') class CacheAPI(dict): ''' Stub to export any cache implementation API ''' def store(self): ''' Store data in the cache persistence. :return: ''' class CacheDict(CacheAPI): ''' Subclass of dict that will lazily delete items past ttl ''' def __init__(self, ttl, *args, **kwargs): # pylint: disable=W0231 dict.__init__(self, *args, **kwargs) # pylint: disable=W0233 self._ttl = ttl self._key_cache_time = {} def _enforce_ttl_key(self, key): ''' Enforce the TTL to a specific key, delete if its past TTL ''' if key not in self._key_cache_time or self._ttl == 0: return if time.time() - self._key_cache_time[key] > self._ttl: del self._key_cache_time[key] dict.__delitem__(self, key) def __getitem__(self, key): ''' Check if the key is ttld out, then do the get ''' self._enforce_ttl_key(key) return dict.__getitem__(self, key) def __setitem__(self, key, val): ''' Make sure to update the key cache time ''' self._key_cache_time[key] = time.time() dict.__setitem__(self, key, val) def __contains__(self, key): self._enforce_ttl_key(key) return dict.__contains__(self, key) class CacheDisk(CacheDict): ''' Class that represents itself as a dictionary to a consumer but uses a disk-based backend. Serialization and de-serialization is done with msgpack ''' def __init__(self, ttl, path, *args, **kwargs): super(CacheDisk, self).__init__(ttl, *args, **kwargs) self._path = path self._dict = {} self._read() def _enforce_ttl_key(self, key): ''' Enforce the TTL to a specific key, delete if its past TTL ''' if key not in self._key_cache_time or self._ttl == 0: return if time.time() - self._key_cache_time[key] > self._ttl: del self._key_cache_time[key] self._dict.__delitem__(key) def __contains__(self, key): self._enforce_ttl_key(key) return self._dict.__contains__(key) def __repr__(self): ''' Represent CacheDisk. :return: ''' return '<{name} of {length} entries at {memaddr}>'.format( name=self.__class__.__name__, length=len(self), memaddr=hex(id(self))) def __str__(self): ''' String version of this object. :return: ''' return self.__repr__() def __len__(self): ''' Length of the cache storage. :return: ''' return len(self._dict) def __getitem__(self, key): ''' Check if the key is ttld out, then do the get ''' self._enforce_ttl_key(key) item = None if key in self._dict: item = self._dict.__getitem__(key) return item def __setitem__(self, key, val): ''' Make sure to update the key cache time ''' self._key_cache_time[key] = time.time() self._dict.__setitem__(key, val) # Do the same as the parent but also persist self.store() def __delitem__(self, key): ''' Make sure to remove the key cache time ''' del self._key_cache_time[key] self._dict.__delitem__(key) # Do the same as the parent but also persist self.store() def _read(self): ''' Read in from disk ''' if msgpack is None: log.error('Cache cannot be read from the disk: msgpack is missing') elif not os.path.exists(self._path): log.debug('Cache path does not exist for reading: %s', self._path) else: try: with salt.utils.files.fopen(self._path, 'rb') as fp_: cache = salt.utils.data.decode(msgpack.load(fp_, encoding=__salt_system_encoding__)) if "CacheDisk_cachetime" in cache: # new format self._dict = cache["CacheDisk_data"] self._key_cache_time = cache["CacheDisk_cachetime"] else: # old format self._dict = cache timestamp = os.path.getmtime(self._path) for key in self._dict: self._key_cache_time[key] = timestamp if log.isEnabledFor(logging.DEBUG): log.debug('Disk cache retrieved: %s', cache) except (IOError, OSError) as err: log.error('Error while reading disk cache from %s: %s', self._path, err) def store(self): ''' Write content of the entire cache to disk ''' if msgpack is None: log.error('Cache cannot be stored on disk: msgpack is missing') else: # TODO Dir hashing? try: with salt.utils.files.fopen(self._path, 'wb+') as fp_: cache = { "CacheDisk_data": self._dict, "CacheDisk_cachetime": self._key_cache_time } msgpack.dump(cache, fp_, use_bin_type=True) except (IOError, OSError) as err: log.error('Error storing cache data to the disk: %s', err) class CacheCli(object): ''' Connection client for the ConCache. Should be used by all components that need the list of currently connected minions ''' def __init__(self, opts): ''' Sets up the zmq-connection to the ConCache ''' self.opts = opts self.serial = salt.payload.Serial(self.opts.get('serial', '')) self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc') self.cache_upd_sock = os.path.join( self.opts['sock_dir'], 'con_upd.ipc') context = zmq.Context() # the socket for talking to the cache self.creq_out = context.socket(zmq.REQ) self.creq_out.setsockopt(zmq.LINGER, 100) self.creq_out.connect('ipc://' + self.cache_sock) # the socket for sending updates to the cache self.cupd_out = context.socket(zmq.PUB) self.cupd_out.setsockopt(zmq.LINGER, 1) self.cupd_out.connect('ipc://' + self.cache_upd_sock) def put_cache(self, minions): ''' published the given minions to the ConCache ''' self.cupd_out.send(self.serial.dumps(minions)) def get_cached(self): ''' queries the ConCache for a list of currently connected minions ''' msg = self.serial.dumps('minions') self.creq_out.send(msg) min_list = self.serial.loads(self.creq_out.recv()) return min_list class CacheRegex(object): ''' Create a regular expression object cache for the most frequently used patterns to minimize compilation of the same patterns over and over again ''' def __init__(self, prepend='', append='', size=1000, keep_fraction=0.8, max_age=3600): self.prepend = prepend self.append = append self.size = size self.clear_size = int(size - size * (keep_fraction)) if self.clear_size >= size: self.clear_size = int(size/2) + 1 if self.clear_size > size: self.clear_size = size self.max_age = max_age self.cache = {} self.timestamp = time.time() def clear(self): ''' Clear the cache ''' self.cache.clear() def sweep(self): ''' Sweep the cache and remove the outdated or least frequently used entries ''' if self.max_age < time.time() - self.timestamp: self.clear() self.timestamp = time.time() else: paterns = list(self.cache.values()) paterns.sort() for idx in range(self.clear_size): del self.cache[paterns[idx][2]] def get(self, pattern): ''' Get a compiled regular expression object based on pattern and cache it when it is not in the cache already ''' try: self.cache[pattern][0] += 1 return self.cache[pattern][1] except KeyError: pass if len(self.cache) > self.size: self.sweep() regex = re.compile('{0}{1}{2}'.format( self.prepend, pattern, self.append)) self.cache[pattern] = [1, regex, pattern, time.time()] return regex class ContextCache(object): def __init__(self, opts, name): ''' Create a context cache ''' self.opts = opts self.cache_path = os.path.join(opts['cachedir'], 'context', '{0}.p'.format(name)) self.serial = salt.payload.Serial(self.opts) def cache_context(self, context): ''' Cache the given context to disk ''' if not os.path.isdir(os.path.dirname(self.cache_path)): os.mkdir(os.path.dirname(self.cache_path)) with salt.utils.files.fopen(self.cache_path, 'w+b') as cache: self.serial.dump(context, cache) def get_cache_context(self): ''' Retrieve a context cache from disk ''' with salt.utils.files.fopen(self.cache_path, 'rb') as cache: return salt.utils.data.decode(self.serial.load(cache)) # test code for the CacheCli if __name__ == '__main__': opts = salt.config.master_config('/etc/salt/master') ccli = CacheCli(opts) ccli.put_cache(['test1', 'test10', 'test34']) ccli.put_cache(['test12']) ccli.put_cache(['test18']) ccli.put_cache(['test21']) print('minions: {0}'.format(ccli.get_cached()))
saltstack/salt
salt/utils/cache.py
CacheDict._enforce_ttl_key
python
def _enforce_ttl_key(self, key): ''' Enforce the TTL to a specific key, delete if its past TTL ''' if key not in self._key_cache_time or self._ttl == 0: return if time.time() - self._key_cache_time[key] > self._ttl: del self._key_cache_time[key] dict.__delitem__(self, key)
Enforce the TTL to a specific key, delete if its past TTL
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L65-L73
null
class CacheDict(CacheAPI): ''' Subclass of dict that will lazily delete items past ttl ''' def __init__(self, ttl, *args, **kwargs): # pylint: disable=W0231 dict.__init__(self, *args, **kwargs) # pylint: disable=W0233 self._ttl = ttl self._key_cache_time = {} def __getitem__(self, key): ''' Check if the key is ttld out, then do the get ''' self._enforce_ttl_key(key) return dict.__getitem__(self, key) def __setitem__(self, key, val): ''' Make sure to update the key cache time ''' self._key_cache_time[key] = time.time() dict.__setitem__(self, key, val) def __contains__(self, key): self._enforce_ttl_key(key) return dict.__contains__(self, key)
saltstack/salt
salt/utils/cache.py
CacheDisk._enforce_ttl_key
python
def _enforce_ttl_key(self, key): ''' Enforce the TTL to a specific key, delete if its past TTL ''' if key not in self._key_cache_time or self._ttl == 0: return if time.time() - self._key_cache_time[key] > self._ttl: del self._key_cache_time[key] self._dict.__delitem__(key)
Enforce the TTL to a specific key, delete if its past TTL
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L106-L114
null
class CacheDisk(CacheDict): ''' Class that represents itself as a dictionary to a consumer but uses a disk-based backend. Serialization and de-serialization is done with msgpack ''' def __init__(self, ttl, path, *args, **kwargs): super(CacheDisk, self).__init__(ttl, *args, **kwargs) self._path = path self._dict = {} self._read() def __contains__(self, key): self._enforce_ttl_key(key) return self._dict.__contains__(key) def __repr__(self): ''' Represent CacheDisk. :return: ''' return '<{name} of {length} entries at {memaddr}>'.format( name=self.__class__.__name__, length=len(self), memaddr=hex(id(self))) def __str__(self): ''' String version of this object. :return: ''' return self.__repr__() def __len__(self): ''' Length of the cache storage. :return: ''' return len(self._dict) def __getitem__(self, key): ''' Check if the key is ttld out, then do the get ''' self._enforce_ttl_key(key) item = None if key in self._dict: item = self._dict.__getitem__(key) return item def __setitem__(self, key, val): ''' Make sure to update the key cache time ''' self._key_cache_time[key] = time.time() self._dict.__setitem__(key, val) # Do the same as the parent but also persist self.store() def __delitem__(self, key): ''' Make sure to remove the key cache time ''' del self._key_cache_time[key] self._dict.__delitem__(key) # Do the same as the parent but also persist self.store() def _read(self): ''' Read in from disk ''' if msgpack is None: log.error('Cache cannot be read from the disk: msgpack is missing') elif not os.path.exists(self._path): log.debug('Cache path does not exist for reading: %s', self._path) else: try: with salt.utils.files.fopen(self._path, 'rb') as fp_: cache = salt.utils.data.decode(msgpack.load(fp_, encoding=__salt_system_encoding__)) if "CacheDisk_cachetime" in cache: # new format self._dict = cache["CacheDisk_data"] self._key_cache_time = cache["CacheDisk_cachetime"] else: # old format self._dict = cache timestamp = os.path.getmtime(self._path) for key in self._dict: self._key_cache_time[key] = timestamp if log.isEnabledFor(logging.DEBUG): log.debug('Disk cache retrieved: %s', cache) except (IOError, OSError) as err: log.error('Error while reading disk cache from %s: %s', self._path, err) def store(self): ''' Write content of the entire cache to disk ''' if msgpack is None: log.error('Cache cannot be stored on disk: msgpack is missing') else: # TODO Dir hashing? try: with salt.utils.files.fopen(self._path, 'wb+') as fp_: cache = { "CacheDisk_data": self._dict, "CacheDisk_cachetime": self._key_cache_time } msgpack.dump(cache, fp_, use_bin_type=True) except (IOError, OSError) as err: log.error('Error storing cache data to the disk: %s', err)
saltstack/salt
salt/utils/cache.py
CacheDisk._read
python
def _read(self): ''' Read in from disk ''' if msgpack is None: log.error('Cache cannot be read from the disk: msgpack is missing') elif not os.path.exists(self._path): log.debug('Cache path does not exist for reading: %s', self._path) else: try: with salt.utils.files.fopen(self._path, 'rb') as fp_: cache = salt.utils.data.decode(msgpack.load(fp_, encoding=__salt_system_encoding__)) if "CacheDisk_cachetime" in cache: # new format self._dict = cache["CacheDisk_data"] self._key_cache_time = cache["CacheDisk_cachetime"] else: # old format self._dict = cache timestamp = os.path.getmtime(self._path) for key in self._dict: self._key_cache_time[key] = timestamp if log.isEnabledFor(logging.DEBUG): log.debug('Disk cache retrieved: %s', cache) except (IOError, OSError) as err: log.error('Error while reading disk cache from %s: %s', self._path, err)
Read in from disk
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L172-L195
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n", "def unpack(stream, **kwargs):\n '''\n .. versionadded:: 2018.3.4\n\n Wraps msgpack.unpack.\n\n By default, this function uses the msgpack module and falls back to\n msgpack_pure, if the msgpack is not available. You can pass an alternate\n msgpack module using the _msgpack_module argument.\n '''\n msgpack_module = kwargs.pop('_msgpack_module', msgpack)\n return msgpack_module.unpack(stream, **kwargs)\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n" ]
class CacheDisk(CacheDict): ''' Class that represents itself as a dictionary to a consumer but uses a disk-based backend. Serialization and de-serialization is done with msgpack ''' def __init__(self, ttl, path, *args, **kwargs): super(CacheDisk, self).__init__(ttl, *args, **kwargs) self._path = path self._dict = {} self._read() def _enforce_ttl_key(self, key): ''' Enforce the TTL to a specific key, delete if its past TTL ''' if key not in self._key_cache_time or self._ttl == 0: return if time.time() - self._key_cache_time[key] > self._ttl: del self._key_cache_time[key] self._dict.__delitem__(key) def __contains__(self, key): self._enforce_ttl_key(key) return self._dict.__contains__(key) def __repr__(self): ''' Represent CacheDisk. :return: ''' return '<{name} of {length} entries at {memaddr}>'.format( name=self.__class__.__name__, length=len(self), memaddr=hex(id(self))) def __str__(self): ''' String version of this object. :return: ''' return self.__repr__() def __len__(self): ''' Length of the cache storage. :return: ''' return len(self._dict) def __getitem__(self, key): ''' Check if the key is ttld out, then do the get ''' self._enforce_ttl_key(key) item = None if key in self._dict: item = self._dict.__getitem__(key) return item def __setitem__(self, key, val): ''' Make sure to update the key cache time ''' self._key_cache_time[key] = time.time() self._dict.__setitem__(key, val) # Do the same as the parent but also persist self.store() def __delitem__(self, key): ''' Make sure to remove the key cache time ''' del self._key_cache_time[key] self._dict.__delitem__(key) # Do the same as the parent but also persist self.store() def store(self): ''' Write content of the entire cache to disk ''' if msgpack is None: log.error('Cache cannot be stored on disk: msgpack is missing') else: # TODO Dir hashing? try: with salt.utils.files.fopen(self._path, 'wb+') as fp_: cache = { "CacheDisk_data": self._dict, "CacheDisk_cachetime": self._key_cache_time } msgpack.dump(cache, fp_, use_bin_type=True) except (IOError, OSError) as err: log.error('Error storing cache data to the disk: %s', err)
saltstack/salt
salt/utils/cache.py
CacheDisk.store
python
def store(self): ''' Write content of the entire cache to disk ''' if msgpack is None: log.error('Cache cannot be stored on disk: msgpack is missing') else: # TODO Dir hashing? try: with salt.utils.files.fopen(self._path, 'wb+') as fp_: cache = { "CacheDisk_data": self._dict, "CacheDisk_cachetime": self._key_cache_time } msgpack.dump(cache, fp_, use_bin_type=True) except (IOError, OSError) as err: log.error('Error storing cache data to the disk: %s', err)
Write content of the entire cache to disk
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L197-L213
[ "def pack(o, stream, **kwargs):\n '''\n .. versionadded:: 2018.3.4\n\n Wraps msgpack.pack and ensures that the passed object is unwrapped if it is\n a proxy.\n\n By default, this function uses the msgpack module and falls back to\n msgpack_pure, if the msgpack is not available. You can pass an alternate\n msgpack module using the _msgpack_module argument.\n '''\n msgpack_module = kwargs.pop('_msgpack_module', msgpack)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n return msgpack_module.pack(o, stream, default=_enc_func, **kwargs)\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n" ]
class CacheDisk(CacheDict): ''' Class that represents itself as a dictionary to a consumer but uses a disk-based backend. Serialization and de-serialization is done with msgpack ''' def __init__(self, ttl, path, *args, **kwargs): super(CacheDisk, self).__init__(ttl, *args, **kwargs) self._path = path self._dict = {} self._read() def _enforce_ttl_key(self, key): ''' Enforce the TTL to a specific key, delete if its past TTL ''' if key not in self._key_cache_time or self._ttl == 0: return if time.time() - self._key_cache_time[key] > self._ttl: del self._key_cache_time[key] self._dict.__delitem__(key) def __contains__(self, key): self._enforce_ttl_key(key) return self._dict.__contains__(key) def __repr__(self): ''' Represent CacheDisk. :return: ''' return '<{name} of {length} entries at {memaddr}>'.format( name=self.__class__.__name__, length=len(self), memaddr=hex(id(self))) def __str__(self): ''' String version of this object. :return: ''' return self.__repr__() def __len__(self): ''' Length of the cache storage. :return: ''' return len(self._dict) def __getitem__(self, key): ''' Check if the key is ttld out, then do the get ''' self._enforce_ttl_key(key) item = None if key in self._dict: item = self._dict.__getitem__(key) return item def __setitem__(self, key, val): ''' Make sure to update the key cache time ''' self._key_cache_time[key] = time.time() self._dict.__setitem__(key, val) # Do the same as the parent but also persist self.store() def __delitem__(self, key): ''' Make sure to remove the key cache time ''' del self._key_cache_time[key] self._dict.__delitem__(key) # Do the same as the parent but also persist self.store() def _read(self): ''' Read in from disk ''' if msgpack is None: log.error('Cache cannot be read from the disk: msgpack is missing') elif not os.path.exists(self._path): log.debug('Cache path does not exist for reading: %s', self._path) else: try: with salt.utils.files.fopen(self._path, 'rb') as fp_: cache = salt.utils.data.decode(msgpack.load(fp_, encoding=__salt_system_encoding__)) if "CacheDisk_cachetime" in cache: # new format self._dict = cache["CacheDisk_data"] self._key_cache_time = cache["CacheDisk_cachetime"] else: # old format self._dict = cache timestamp = os.path.getmtime(self._path) for key in self._dict: self._key_cache_time[key] = timestamp if log.isEnabledFor(logging.DEBUG): log.debug('Disk cache retrieved: %s', cache) except (IOError, OSError) as err: log.error('Error while reading disk cache from %s: %s', self._path, err)
saltstack/salt
salt/utils/cache.py
CacheCli.put_cache
python
def put_cache(self, minions): ''' published the given minions to the ConCache ''' self.cupd_out.send(self.serial.dumps(minions))
published the given minions to the ConCache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L244-L248
[ "def dumps(self, msg, use_bin_type=False):\n '''\n Run the correct dumps serialization format\n\n :param use_bin_type: Useful for Python 3 support. Tells msgpack to\n differentiate between 'str' and 'bytes' types\n by encoding them differently.\n Since this changes the wire protocol, this\n option should not be used outside of IPC.\n '''\n def ext_type_encoder(obj):\n if isinstance(obj, six.integer_types):\n # msgpack can't handle the very long Python longs for jids\n # Convert any very long longs to strings\n return six.text_type(obj)\n elif isinstance(obj, (datetime.datetime, datetime.date)):\n # msgpack doesn't support datetime.datetime and datetime.date datatypes.\n # So here we have converted these types to custom datatype\n # This is msgpack Extended types numbered 78\n return msgpack.ExtType(78, salt.utils.stringutils.to_bytes(\n obj.strftime('%Y%m%dT%H:%M:%S.%f')))\n # The same for immutable types\n elif isinstance(obj, immutabletypes.ImmutableDict):\n return dict(obj)\n elif isinstance(obj, immutabletypes.ImmutableList):\n return list(obj)\n elif isinstance(obj, (set, immutabletypes.ImmutableSet)):\n # msgpack can't handle set so translate it to tuple\n return tuple(obj)\n elif isinstance(obj, CaseInsensitiveDict):\n return dict(obj)\n # Nothing known exceptions found. Let msgpack raise it's own.\n return obj\n\n try:\n if msgpack.version >= (0, 4, 0):\n # msgpack only supports 'use_bin_type' starting in 0.4.0.\n # Due to this, if we don't need it, don't pass it at all so\n # that under Python 2 we can still work with older versions\n # of msgpack.\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n except (OverflowError, msgpack.exceptions.PackValueError):\n # msgpack<=0.4.6 don't call ext encoder on very long integers raising the error instead.\n # Convert any very long longs to strings and call dumps again.\n def verylong_encoder(obj, context):\n # Make sure we catch recursion here.\n objid = id(obj)\n if objid in context:\n return '<Recursion on {} with id={}>'.format(type(obj).__name__, id(obj))\n context.add(objid)\n\n if isinstance(obj, dict):\n for key, value in six.iteritems(obj.copy()):\n obj[key] = verylong_encoder(value, context)\n return dict(obj)\n elif isinstance(obj, (list, tuple)):\n obj = list(obj)\n for idx, entry in enumerate(obj):\n obj[idx] = verylong_encoder(entry, context)\n return obj\n # A value of an Integer object is limited from -(2^63) upto (2^64)-1 by MessagePack\n # spec. Here we care only of JIDs that are positive integers.\n if isinstance(obj, six.integer_types) and obj >= pow(2, 64):\n return six.text_type(obj)\n else:\n return obj\n\n msg = verylong_encoder(msg, set())\n if msgpack.version >= (0, 4, 0):\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n" ]
class CacheCli(object): ''' Connection client for the ConCache. Should be used by all components that need the list of currently connected minions ''' def __init__(self, opts): ''' Sets up the zmq-connection to the ConCache ''' self.opts = opts self.serial = salt.payload.Serial(self.opts.get('serial', '')) self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc') self.cache_upd_sock = os.path.join( self.opts['sock_dir'], 'con_upd.ipc') context = zmq.Context() # the socket for talking to the cache self.creq_out = context.socket(zmq.REQ) self.creq_out.setsockopt(zmq.LINGER, 100) self.creq_out.connect('ipc://' + self.cache_sock) # the socket for sending updates to the cache self.cupd_out = context.socket(zmq.PUB) self.cupd_out.setsockopt(zmq.LINGER, 1) self.cupd_out.connect('ipc://' + self.cache_upd_sock) def get_cached(self): ''' queries the ConCache for a list of currently connected minions ''' msg = self.serial.dumps('minions') self.creq_out.send(msg) min_list = self.serial.loads(self.creq_out.recv()) return min_list
saltstack/salt
salt/utils/cache.py
CacheCli.get_cached
python
def get_cached(self): ''' queries the ConCache for a list of currently connected minions ''' msg = self.serial.dumps('minions') self.creq_out.send(msg) min_list = self.serial.loads(self.creq_out.recv()) return min_list
queries the ConCache for a list of currently connected minions
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L250-L257
[ "def loads(self, msg, encoding=None, raw=False):\n '''\n Run the correct loads serialization format\n\n :param encoding: Useful for Python 3 support. If the msgpack data\n was encoded using \"use_bin_type=True\", this will\n differentiate between the 'bytes' type and the\n 'str' type by decoding contents with 'str' type\n to what the encoding was set as. Recommended\n encoding is 'utf-8' when using Python 3.\n If the msgpack data was not encoded using\n \"use_bin_type=True\", it will try to decode\n all 'bytes' and 'str' data (the distinction has\n been lost in this case) to what the encoding is\n set as. In this case, it will fail if any of\n the contents cannot be converted.\n '''\n try:\n def ext_type_decoder(code, data):\n if code == 78:\n data = salt.utils.stringutils.to_unicode(data)\n return datetime.datetime.strptime(data, '%Y%m%dT%H:%M:%S.%f')\n return data\n\n gc.disable() # performance optimization for msgpack\n if msgpack.version >= (0, 4, 0):\n # msgpack only supports 'encoding' starting in 0.4.0.\n # Due to this, if we don't need it, don't pass it at all so\n # that under Python 2 we can still work with older versions\n # of msgpack.\n try:\n ret = salt.utils.msgpack.loads(msg, use_list=True,\n ext_hook=ext_type_decoder,\n encoding=encoding,\n _msgpack_module=msgpack)\n except UnicodeDecodeError:\n # msg contains binary data\n ret = msgpack.loads(msg, use_list=True, ext_hook=ext_type_decoder)\n else:\n ret = salt.utils.msgpack.loads(msg, use_list=True,\n ext_hook=ext_type_decoder,\n _msgpack_module=msgpack)\n if six.PY3 and encoding is None and not raw:\n ret = salt.transport.frame.decode_embedded_strs(ret)\n except Exception as exc:\n log.critical(\n 'Could not deserialize msgpack message. This often happens '\n 'when trying to read a file not in binary mode. '\n 'To see message payload, enable debug logging and retry. '\n 'Exception: %s', exc\n )\n log.debug('Msgpack deserialization failure on message: %s', msg)\n gc.collect()\n raise\n finally:\n gc.enable()\n return ret\n", "def dumps(self, msg, use_bin_type=False):\n '''\n Run the correct dumps serialization format\n\n :param use_bin_type: Useful for Python 3 support. Tells msgpack to\n differentiate between 'str' and 'bytes' types\n by encoding them differently.\n Since this changes the wire protocol, this\n option should not be used outside of IPC.\n '''\n def ext_type_encoder(obj):\n if isinstance(obj, six.integer_types):\n # msgpack can't handle the very long Python longs for jids\n # Convert any very long longs to strings\n return six.text_type(obj)\n elif isinstance(obj, (datetime.datetime, datetime.date)):\n # msgpack doesn't support datetime.datetime and datetime.date datatypes.\n # So here we have converted these types to custom datatype\n # This is msgpack Extended types numbered 78\n return msgpack.ExtType(78, salt.utils.stringutils.to_bytes(\n obj.strftime('%Y%m%dT%H:%M:%S.%f')))\n # The same for immutable types\n elif isinstance(obj, immutabletypes.ImmutableDict):\n return dict(obj)\n elif isinstance(obj, immutabletypes.ImmutableList):\n return list(obj)\n elif isinstance(obj, (set, immutabletypes.ImmutableSet)):\n # msgpack can't handle set so translate it to tuple\n return tuple(obj)\n elif isinstance(obj, CaseInsensitiveDict):\n return dict(obj)\n # Nothing known exceptions found. Let msgpack raise it's own.\n return obj\n\n try:\n if msgpack.version >= (0, 4, 0):\n # msgpack only supports 'use_bin_type' starting in 0.4.0.\n # Due to this, if we don't need it, don't pass it at all so\n # that under Python 2 we can still work with older versions\n # of msgpack.\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n except (OverflowError, msgpack.exceptions.PackValueError):\n # msgpack<=0.4.6 don't call ext encoder on very long integers raising the error instead.\n # Convert any very long longs to strings and call dumps again.\n def verylong_encoder(obj, context):\n # Make sure we catch recursion here.\n objid = id(obj)\n if objid in context:\n return '<Recursion on {} with id={}>'.format(type(obj).__name__, id(obj))\n context.add(objid)\n\n if isinstance(obj, dict):\n for key, value in six.iteritems(obj.copy()):\n obj[key] = verylong_encoder(value, context)\n return dict(obj)\n elif isinstance(obj, (list, tuple)):\n obj = list(obj)\n for idx, entry in enumerate(obj):\n obj[idx] = verylong_encoder(entry, context)\n return obj\n # A value of an Integer object is limited from -(2^63) upto (2^64)-1 by MessagePack\n # spec. Here we care only of JIDs that are positive integers.\n if isinstance(obj, six.integer_types) and obj >= pow(2, 64):\n return six.text_type(obj)\n else:\n return obj\n\n msg = verylong_encoder(msg, set())\n if msgpack.version >= (0, 4, 0):\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n use_bin_type=use_bin_type,\n _msgpack_module=msgpack)\n else:\n return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,\n _msgpack_module=msgpack)\n" ]
class CacheCli(object): ''' Connection client for the ConCache. Should be used by all components that need the list of currently connected minions ''' def __init__(self, opts): ''' Sets up the zmq-connection to the ConCache ''' self.opts = opts self.serial = salt.payload.Serial(self.opts.get('serial', '')) self.cache_sock = os.path.join(self.opts['sock_dir'], 'con_cache.ipc') self.cache_upd_sock = os.path.join( self.opts['sock_dir'], 'con_upd.ipc') context = zmq.Context() # the socket for talking to the cache self.creq_out = context.socket(zmq.REQ) self.creq_out.setsockopt(zmq.LINGER, 100) self.creq_out.connect('ipc://' + self.cache_sock) # the socket for sending updates to the cache self.cupd_out = context.socket(zmq.PUB) self.cupd_out.setsockopt(zmq.LINGER, 1) self.cupd_out.connect('ipc://' + self.cache_upd_sock) def put_cache(self, minions): ''' published the given minions to the ConCache ''' self.cupd_out.send(self.serial.dumps(minions))
saltstack/salt
salt/utils/cache.py
CacheRegex.sweep
python
def sweep(self): ''' Sweep the cache and remove the outdated or least frequently used entries ''' if self.max_age < time.time() - self.timestamp: self.clear() self.timestamp = time.time() else: paterns = list(self.cache.values()) paterns.sort() for idx in range(self.clear_size): del self.cache[paterns[idx][2]]
Sweep the cache and remove the outdated or least frequently used entries
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L286-L298
[ "def clear(self):\n '''\n Clear the cache\n '''\n self.cache.clear()\n" ]
class CacheRegex(object): ''' Create a regular expression object cache for the most frequently used patterns to minimize compilation of the same patterns over and over again ''' def __init__(self, prepend='', append='', size=1000, keep_fraction=0.8, max_age=3600): self.prepend = prepend self.append = append self.size = size self.clear_size = int(size - size * (keep_fraction)) if self.clear_size >= size: self.clear_size = int(size/2) + 1 if self.clear_size > size: self.clear_size = size self.max_age = max_age self.cache = {} self.timestamp = time.time() def clear(self): ''' Clear the cache ''' self.cache.clear() def get(self, pattern): ''' Get a compiled regular expression object based on pattern and cache it when it is not in the cache already ''' try: self.cache[pattern][0] += 1 return self.cache[pattern][1] except KeyError: pass if len(self.cache) > self.size: self.sweep() regex = re.compile('{0}{1}{2}'.format( self.prepend, pattern, self.append)) self.cache[pattern] = [1, regex, pattern, time.time()] return regex
saltstack/salt
salt/utils/cache.py
CacheRegex.get
python
def get(self, pattern): ''' Get a compiled regular expression object based on pattern and cache it when it is not in the cache already ''' try: self.cache[pattern][0] += 1 return self.cache[pattern][1] except KeyError: pass if len(self.cache) > self.size: self.sweep() regex = re.compile('{0}{1}{2}'.format( self.prepend, pattern, self.append)) self.cache[pattern] = [1, regex, pattern, time.time()] return regex
Get a compiled regular expression object based on pattern and cache it when it is not in the cache already
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L300-L315
[ "def sweep(self):\n '''\n Sweep the cache and remove the outdated or least frequently\n used entries\n '''\n if self.max_age < time.time() - self.timestamp:\n self.clear()\n self.timestamp = time.time()\n else:\n paterns = list(self.cache.values())\n paterns.sort()\n for idx in range(self.clear_size):\n del self.cache[paterns[idx][2]]\n" ]
class CacheRegex(object): ''' Create a regular expression object cache for the most frequently used patterns to minimize compilation of the same patterns over and over again ''' def __init__(self, prepend='', append='', size=1000, keep_fraction=0.8, max_age=3600): self.prepend = prepend self.append = append self.size = size self.clear_size = int(size - size * (keep_fraction)) if self.clear_size >= size: self.clear_size = int(size/2) + 1 if self.clear_size > size: self.clear_size = size self.max_age = max_age self.cache = {} self.timestamp = time.time() def clear(self): ''' Clear the cache ''' self.cache.clear() def sweep(self): ''' Sweep the cache and remove the outdated or least frequently used entries ''' if self.max_age < time.time() - self.timestamp: self.clear() self.timestamp = time.time() else: paterns = list(self.cache.values()) paterns.sort() for idx in range(self.clear_size): del self.cache[paterns[idx][2]]
saltstack/salt
salt/utils/cache.py
ContextCache.cache_context
python
def cache_context(self, context): ''' Cache the given context to disk ''' if not os.path.isdir(os.path.dirname(self.cache_path)): os.mkdir(os.path.dirname(self.cache_path)) with salt.utils.files.fopen(self.cache_path, 'w+b') as cache: self.serial.dump(context, cache)
Cache the given context to disk
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L327-L334
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def dump(self, msg, fn_):\n '''\n Serialize the correct data into the named file object\n '''\n if six.PY2:\n fn_.write(self.dumps(msg))\n else:\n # When using Python 3, write files in such a way\n # that the 'bytes' and 'str' types are distinguishable\n # by using \"use_bin_type=True\".\n fn_.write(self.dumps(msg, use_bin_type=True))\n fn_.close()\n" ]
class ContextCache(object): def __init__(self, opts, name): ''' Create a context cache ''' self.opts = opts self.cache_path = os.path.join(opts['cachedir'], 'context', '{0}.p'.format(name)) self.serial = salt.payload.Serial(self.opts) def get_cache_context(self): ''' Retrieve a context cache from disk ''' with salt.utils.files.fopen(self.cache_path, 'rb') as cache: return salt.utils.data.decode(self.serial.load(cache))
saltstack/salt
salt/utils/cache.py
ContextCache.get_cache_context
python
def get_cache_context(self): ''' Retrieve a context cache from disk ''' with salt.utils.files.fopen(self.cache_path, 'rb') as cache: return salt.utils.data.decode(self.serial.load(cache))
Retrieve a context cache from disk
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L336-L341
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def load(self, fn_):\n '''\n Run the correct serialization to load a file\n '''\n data = fn_.read()\n fn_.close()\n if data:\n if six.PY3:\n return self.loads(data, encoding='utf-8')\n else:\n return self.loads(data)\n" ]
class ContextCache(object): def __init__(self, opts, name): ''' Create a context cache ''' self.opts = opts self.cache_path = os.path.join(opts['cachedir'], 'context', '{0}.p'.format(name)) self.serial = salt.payload.Serial(self.opts) def cache_context(self, context): ''' Cache the given context to disk ''' if not os.path.isdir(os.path.dirname(self.cache_path)): os.mkdir(os.path.dirname(self.cache_path)) with salt.utils.files.fopen(self.cache_path, 'w+b') as cache: self.serial.dump(context, cache)
saltstack/salt
salt/utils/doc.py
strip_rst
python
def strip_rst(docs): ''' Strip/replace reStructuredText directives in docstrings ''' for func, docstring in six.iteritems(docs): log.debug('Stripping docstring for %s', func) if not docstring: continue docstring_new = docstring if six.PY3 else salt.utils.data.encode(docstring) for regex, repl in ( (r' *.. code-block:: \S+\n{1,2}', ''), ('.. note::', 'Note:'), ('.. warning::', 'Warning:'), ('.. versionadded::', 'New in version'), ('.. versionchanged::', 'Changed in version')): if six.PY2: regex = salt.utils.data.encode(regex) repl = salt.utils.data.encode(repl) try: docstring_new = re.sub(regex, repl, docstring_new) except Exception: log.debug( 'Exception encountered while matching regex %r to ' 'docstring for function %s', regex, func, exc_info=True ) if six.PY2: docstring_new = salt.utils.data.decode(docstring_new) if docstring != docstring_new: docs[func] = docstring_new return docs
Strip/replace reStructuredText directives in docstrings
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/doc.py#L16-L46
[ "def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n", "def encode(data, encoding=None, errors='strict', keep=False,\n preserve_dict_class=False, preserve_tuples=False):\n '''\n Generic function which will encode whichever type is passed, if necessary\n\n If `strict` is True, and `keep` is False, and we fail to encode, a\n UnicodeEncodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where encoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs.\n '''\n if isinstance(data, Mapping):\n return encode_dict(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, list):\n return encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, tuple):\n return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \\\n if preserve_tuples \\\n else encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n else:\n try:\n return salt.utils.stringutils.to_bytes(data, encoding, errors)\n except TypeError:\n # to_bytes raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply\n # means we are going to leave the value as-is.\n pass\n except UnicodeEncodeError:\n if not keep:\n raise\n return data\n", "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Functions for analyzing/parsing docstrings ''' from __future__ import absolute_import, print_function, unicode_literals import logging import re import salt.utils.data from salt.ext import six log = logging.getLogger(__name__) def parse_docstring(docstring): ''' Parse a docstring into its parts. Currently only parses dependencies, can be extended to parse whatever is needed. Parses into a dictionary: { 'full': full docstring, 'deps': list of dependencies (empty list if none) } ''' # First try with regex search for :depends: ret = {'full': docstring} regex = r'([ \t]*):depends:[ \t]+- (\w+)[^\n]*\n(\1[ \t]+- (\w+)[^\n]*\n)*' match = re.search(regex, docstring, re.M) if match: deps = [] regex = r'- (\w+)' for line in match.group(0).strip().splitlines(): deps.append(re.search(regex, line).group(1)) ret['deps'] = deps return ret # Try searching for a one-liner instead else: txt = 'Required python modules: ' data = docstring.splitlines() dep_list = list(x for x in data if x.strip().startswith(txt)) if not dep_list: ret['deps'] = [] return ret deps = dep_list[0].replace(txt, '').strip().split(', ') ret['deps'] = deps return ret
saltstack/salt
salt/utils/doc.py
parse_docstring
python
def parse_docstring(docstring): ''' Parse a docstring into its parts. Currently only parses dependencies, can be extended to parse whatever is needed. Parses into a dictionary: { 'full': full docstring, 'deps': list of dependencies (empty list if none) } ''' # First try with regex search for :depends: ret = {'full': docstring} regex = r'([ \t]*):depends:[ \t]+- (\w+)[^\n]*\n(\1[ \t]+- (\w+)[^\n]*\n)*' match = re.search(regex, docstring, re.M) if match: deps = [] regex = r'- (\w+)' for line in match.group(0).strip().splitlines(): deps.append(re.search(regex, line).group(1)) ret['deps'] = deps return ret # Try searching for a one-liner instead else: txt = 'Required python modules: ' data = docstring.splitlines() dep_list = list(x for x in data if x.strip().startswith(txt)) if not dep_list: ret['deps'] = [] return ret deps = dep_list[0].replace(txt, '').strip().split(', ') ret['deps'] = deps return ret
Parse a docstring into its parts. Currently only parses dependencies, can be extended to parse whatever is needed. Parses into a dictionary: { 'full': full docstring, 'deps': list of dependencies (empty list if none) }
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/doc.py#L49-L83
null
# -*- coding: utf-8 -*- ''' Functions for analyzing/parsing docstrings ''' from __future__ import absolute_import, print_function, unicode_literals import logging import re import salt.utils.data from salt.ext import six log = logging.getLogger(__name__) def strip_rst(docs): ''' Strip/replace reStructuredText directives in docstrings ''' for func, docstring in six.iteritems(docs): log.debug('Stripping docstring for %s', func) if not docstring: continue docstring_new = docstring if six.PY3 else salt.utils.data.encode(docstring) for regex, repl in ( (r' *.. code-block:: \S+\n{1,2}', ''), ('.. note::', 'Note:'), ('.. warning::', 'Warning:'), ('.. versionadded::', 'New in version'), ('.. versionchanged::', 'Changed in version')): if six.PY2: regex = salt.utils.data.encode(regex) repl = salt.utils.data.encode(repl) try: docstring_new = re.sub(regex, repl, docstring_new) except Exception: log.debug( 'Exception encountered while matching regex %r to ' 'docstring for function %s', regex, func, exc_info=True ) if six.PY2: docstring_new = salt.utils.data.decode(docstring_new) if docstring != docstring_new: docs[func] = docstring_new return docs
saltstack/salt
salt/states/boto_elasticache.py
present
python
def present( name, engine=None, cache_node_type=None, num_cache_nodes=None, preferred_availability_zone=None, port=None, cache_parameter_group_name=None, cache_security_group_names=None, replication_group_id=None, auto_minor_version_upgrade=True, security_group_ids=None, cache_subnet_group_name=None, engine_version=None, notification_topic_arn=None, preferred_maintenance_window=None, wait=None, region=None, key=None, keyid=None, profile=None): ''' Ensure the cache cluster exists. name Name of the cache cluster (cache cluster id). engine The name of the cache engine to be used for this cache cluster. Valid values are memcached or redis. cache_node_type The compute and memory capacity of the nodes in the cache cluster. cache.t1.micro, cache.m1.small, etc. See: https://boto.readthedocs.io/en/latest/ref/elasticache.html#boto.elasticache.layer1.ElastiCacheConnection.create_cache_cluster num_cache_nodes The number of cache nodes that the cache cluster will have. preferred_availability_zone The EC2 Availability Zone in which the cache cluster will be created. All cache nodes belonging to a cache cluster are placed in the preferred availability zone. port The port number on which each of the cache nodes will accept connections. cache_parameter_group_name The name of the cache parameter group to associate with this cache cluster. If this argument is omitted, the default cache parameter group for the specified engine will be used. cache_security_group_names A list of cache security group names to associate with this cache cluster. Use this parameter only when you are creating a cluster outside of a VPC. replication_group_id The replication group to which this cache cluster should belong. If this parameter is specified, the cache cluster will be added to the specified replication group as a read replica; otherwise, the cache cluster will be a standalone primary that is not part of any replication group. auto_minor_version_upgrade Determines whether minor engine upgrades will be applied automatically to the cache cluster during the maintenance window. A value of True allows these upgrades to occur; False disables automatic upgrades. security_group_ids One or more VPC security groups associated with the cache cluster. Use this parameter only when you are creating a cluster in a VPC. cache_subnet_group_name The name of the cache subnet group to be used for the cache cluster. Use this parameter only when you are creating a cluster in a VPC. engine_version The version number of the cache engine to be used for this cluster. notification_topic_arn The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (SNS) topic to which notifications will be sent. The Amazon SNS topic owner must be the same as the cache cluster owner. preferred_maintenance_window The weekly time range (in UTC) during which system maintenance can occur. Example: sun:05:00-sun:09:00 wait Boolean. Wait for confirmation from boto that the cluster is in the available state. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if cache_security_group_names and cache_subnet_group_name: _subnet_group = __salt__['boto_elasticache.get_cache_subnet_group']( cache_subnet_group_name, region, key, keyid, profile ) vpc_id = _subnet_group['vpc_id'] if not security_group_ids: security_group_ids = [] _security_group_ids = __salt__['boto_secgroup.convert_to_group_ids']( groups=cache_security_group_names, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile ) security_group_ids.extend(_security_group_ids) cache_security_group_names = None config = __salt__['boto_elasticache.get_config'](name, region, key, keyid, profile) if config is None: msg = 'Failed to retrieve cache cluster info from AWS.' ret['comment'] = msg ret['result'] = None return ret elif not config: if __opts__['test']: msg = 'Cache cluster {0} is set to be created.'.format(name) ret['comment'] = msg ret['result'] = None return ret created = __salt__['boto_elasticache.create']( name=name, num_cache_nodes=num_cache_nodes, cache_node_type=cache_node_type, engine=engine, replication_group_id=replication_group_id, engine_version=engine_version, cache_parameter_group_name=cache_parameter_group_name, cache_subnet_group_name=cache_subnet_group_name, cache_security_group_names=cache_security_group_names, security_group_ids=security_group_ids, preferred_availability_zone=preferred_availability_zone, preferred_maintenance_window=preferred_maintenance_window, port=port, notification_topic_arn=notification_topic_arn, auto_minor_version_upgrade=auto_minor_version_upgrade, wait=wait, region=region, key=key, keyid=keyid, profile=profile) if created: ret['changes']['old'] = None config = __salt__['boto_elasticache.get_config'](name, region, key, keyid, profile) ret['changes']['new'] = config else: ret['result'] = False ret['comment'] = 'Failed to create {0} cache cluster.'.format(name) return ret # TODO: support modification of existing elasticache clusters else: ret['comment'] = 'Cache cluster {0} is present.'.format(name) return ret
Ensure the cache cluster exists. name Name of the cache cluster (cache cluster id). engine The name of the cache engine to be used for this cache cluster. Valid values are memcached or redis. cache_node_type The compute and memory capacity of the nodes in the cache cluster. cache.t1.micro, cache.m1.small, etc. See: https://boto.readthedocs.io/en/latest/ref/elasticache.html#boto.elasticache.layer1.ElastiCacheConnection.create_cache_cluster num_cache_nodes The number of cache nodes that the cache cluster will have. preferred_availability_zone The EC2 Availability Zone in which the cache cluster will be created. All cache nodes belonging to a cache cluster are placed in the preferred availability zone. port The port number on which each of the cache nodes will accept connections. cache_parameter_group_name The name of the cache parameter group to associate with this cache cluster. If this argument is omitted, the default cache parameter group for the specified engine will be used. cache_security_group_names A list of cache security group names to associate with this cache cluster. Use this parameter only when you are creating a cluster outside of a VPC. replication_group_id The replication group to which this cache cluster should belong. If this parameter is specified, the cache cluster will be added to the specified replication group as a read replica; otherwise, the cache cluster will be a standalone primary that is not part of any replication group. auto_minor_version_upgrade Determines whether minor engine upgrades will be applied automatically to the cache cluster during the maintenance window. A value of True allows these upgrades to occur; False disables automatic upgrades. security_group_ids One or more VPC security groups associated with the cache cluster. Use this parameter only when you are creating a cluster in a VPC. cache_subnet_group_name The name of the cache subnet group to be used for the cache cluster. Use this parameter only when you are creating a cluster in a VPC. engine_version The version number of the cache engine to be used for this cluster. notification_topic_arn The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (SNS) topic to which notifications will be sent. The Amazon SNS topic owner must be the same as the cache cluster owner. preferred_maintenance_window The weekly time range (in UTC) during which system maintenance can occur. Example: sun:05:00-sun:09:00 wait Boolean. Wait for confirmation from boto that the cluster is in the available state. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_elasticache.py#L100-L263
null
# -*- coding: utf-8 -*- ''' Manage Elasticache ================== .. versionadded:: 2014.7.0 Create, destroy and update Elasticache clusters. Be aware that this interacts with Amazon's services, and so may incur charges. Note: This module currently only supports creation and deletion of elasticache resources and will not modify clusters when their configuration changes in your state files. This module uses ``boto``, which can be installed via package, or pip. This module accepts explicit elasticache credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More information available `here <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_. If IAM roles are not used you need to specify them either in a pillar file or in the minion's config file: .. code-block:: yaml elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either passed in as a dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. code-block:: yaml Ensure myelasticache exists: boto_elasticache.present: - name: myelasticache - engine: redis - cache_node_type: cache.t1.micro - num_cache_nodes: 1 - notification_topic_arn: arn:aws:sns:us-east-1:879879:my-sns-topic - region: us-east-1 - keyid: GKTADJGHEIQSXMKKRBJ08H - key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs # Using a profile from pillars Ensure myelasticache exists: boto_elasticache.present: - name: myelasticache - engine: redis - cache_node_type: cache.t1.micro - num_cache_nodes: 1 - notification_topic_arn: arn:aws:sns:us-east-1:879879:my-sns-topic - region: us-east-1 - profile: myprofile # Passing in a profile Ensure myelasticache exists: boto_elasticache.present: - name: myelasticache - engine: redis - cache_node_type: cache.t1.micro - num_cache_nodes: 1 - notification_topic_arn: arn:aws:sns:us-east-1:879879:my-sns-topic - region: us-east-1 - profile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto is available. ''' if 'boto_elasticache.exists' in __salt__: return 'boto_elasticache' else: return False def cache_cluster_present(*args, **kwargs): return present(*args, **kwargs) def subnet_group_present(name, subnet_ids=None, subnet_names=None, description=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Ensure ElastiCache subnet group exists. .. versionadded:: 2015.8.0 name The name for the ElastiCache subnet group. This value is stored as a lowercase string. subnet_ids A list of VPC subnet IDs for the cache subnet group. Exclusive with subnet_names. subnet_names A list of VPC subnet names for the cache subnet group. Exclusive with subnet_ids. description Subnet group description. tags A list of tags. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {} } exists = __salt__['boto_elasticache.subnet_group_exists'](name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not exists: if __opts__['test']: ret['comment'] = 'Subnet group {0} is set to be created.'.format(name) ret['result'] = None return ret created = __salt__['boto_elasticache.create_subnet_group'](name=name, subnet_ids=subnet_ids, subnet_names=subnet_names, description=description, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not created: ret['result'] = False ret['comment'] = 'Failed to create {0} subnet group.'.format(name) return ret ret['changes']['old'] = None ret['changes']['new'] = name ret['comment'] = 'Subnet group {0} created.'.format(name) return ret ret['comment'] = 'Subnet group present.' return ret def cache_cluster_absent(*args, **kwargs): return absent(*args, **kwargs) def absent(name, wait=True, region=None, key=None, keyid=None, profile=None): ''' Ensure the named elasticache cluster is deleted. name Name of the cache cluster. wait Boolean. Wait for confirmation from boto that the cluster is in the deleting state. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} is_present = __salt__['boto_elasticache.exists'](name, region, key, keyid, profile) if is_present: if __opts__['test']: ret['comment'] = 'Cache cluster {0} is set to be removed.'.format(name) ret['result'] = None return ret deleted = __salt__['boto_elasticache.delete'](name, wait, region, key, keyid, profile) if deleted: ret['changes']['old'] = name ret['changes']['new'] = None else: ret['result'] = False ret['comment'] = 'Failed to delete {0} cache cluster.'.format(name) else: ret['comment'] = '{0} does not exist in {1}.'.format(name, region) return ret def replication_group_present(*args, **kwargs): return creategroup(*args, **kwargs) def creategroup(name, primary_cluster_id, replication_group_description, wait=None, region=None, key=None, keyid=None, profile=None): ''' Ensure the a replication group is create. name Name of replication group wait Waits for the group to be available primary_cluster_id Name of the master cache node replication_group_description Description for the group region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} is_present = __salt__['boto_elasticache.group_exists'](name, region, key, keyid, profile) if not is_present: if __opts__['test']: ret['comment'] = 'Replication {0} is set to be created.'.format( name) ret['result'] = None created = __salt__['boto_elasticache.create_replication_group'](name, primary_cluster_id, replication_group_description, wait, region, key, keyid, profile) if created: config = __salt__['boto_elasticache.describe_replication_group'](name, region, key, keyid, profile) ret['changes']['old'] = None ret['changes']['new'] = config ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to create {0} replication group.'.format(name) else: ret['comment'] = '{0} replication group exists .'.format(name) ret['result'] = True return ret def subnet_group_absent(name, tags=None, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {} } exists = __salt__['boto_elasticache.subnet_group_exists'](name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not exists: ret['result'] = True ret['comment'] = '{0} ElastiCache subnet group does not exist.'.format(name) return ret if __opts__['test']: ret['comment'] = 'ElastiCache subnet group {0} is set to be removed.'.format(name) ret['result'] = None return ret deleted = __salt__['boto_elasticache.delete_subnet_group'](name, region, key, keyid, profile) if not deleted: ret['result'] = False ret['comment'] = 'Failed to delete {0} ElastiCache subnet group.'.format(name) return ret ret['changes']['old'] = name ret['changes']['new'] = None ret['comment'] = 'ElastiCache subnet group {0} deleted.'.format(name) return ret def replication_group_absent(name, tags=None, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {} } exists = __salt__['boto_elasticache.group_exists'](name=name, region=region, key=key, keyid=keyid, profile=profile) if not exists: ret['result'] = True ret['comment'] = '{0} ElastiCache replication group does not exist.'.format(name) log.info(ret['comment']) return ret if __opts__['test']: ret['comment'] = 'ElastiCache replication group {0} is set to be removed.'.format(name) ret['result'] = True return ret deleted = __salt__['boto_elasticache.delete_replication_group'](name, region, key, keyid, profile) if not deleted: ret['result'] = False log.error(ret['comment']) ret['comment'] = 'Failed to delete {0} ElastiCache replication group.'.format(name) return ret ret['changes']['old'] = name ret['changes']['new'] = None ret['comment'] = 'ElastiCache replication group {0} deleted.'.format(name) log.info(ret['comment']) return ret
saltstack/salt
salt/states/boto_elasticache.py
subnet_group_present
python
def subnet_group_present(name, subnet_ids=None, subnet_names=None, description=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Ensure ElastiCache subnet group exists. .. versionadded:: 2015.8.0 name The name for the ElastiCache subnet group. This value is stored as a lowercase string. subnet_ids A list of VPC subnet IDs for the cache subnet group. Exclusive with subnet_names. subnet_names A list of VPC subnet names for the cache subnet group. Exclusive with subnet_ids. description Subnet group description. tags A list of tags. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {} } exists = __salt__['boto_elasticache.subnet_group_exists'](name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not exists: if __opts__['test']: ret['comment'] = 'Subnet group {0} is set to be created.'.format(name) ret['result'] = None return ret created = __salt__['boto_elasticache.create_subnet_group'](name=name, subnet_ids=subnet_ids, subnet_names=subnet_names, description=description, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not created: ret['result'] = False ret['comment'] = 'Failed to create {0} subnet group.'.format(name) return ret ret['changes']['old'] = None ret['changes']['new'] = name ret['comment'] = 'Subnet group {0} created.'.format(name) return ret ret['comment'] = 'Subnet group present.' return ret
Ensure ElastiCache subnet group exists. .. versionadded:: 2015.8.0 name The name for the ElastiCache subnet group. This value is stored as a lowercase string. subnet_ids A list of VPC subnet IDs for the cache subnet group. Exclusive with subnet_names. subnet_names A list of VPC subnet names for the cache subnet group. Exclusive with subnet_ids. description Subnet group description. tags A list of tags. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_elasticache.py#L266-L329
null
# -*- coding: utf-8 -*- ''' Manage Elasticache ================== .. versionadded:: 2014.7.0 Create, destroy and update Elasticache clusters. Be aware that this interacts with Amazon's services, and so may incur charges. Note: This module currently only supports creation and deletion of elasticache resources and will not modify clusters when their configuration changes in your state files. This module uses ``boto``, which can be installed via package, or pip. This module accepts explicit elasticache credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More information available `here <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_. If IAM roles are not used you need to specify them either in a pillar file or in the minion's config file: .. code-block:: yaml elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either passed in as a dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. code-block:: yaml Ensure myelasticache exists: boto_elasticache.present: - name: myelasticache - engine: redis - cache_node_type: cache.t1.micro - num_cache_nodes: 1 - notification_topic_arn: arn:aws:sns:us-east-1:879879:my-sns-topic - region: us-east-1 - keyid: GKTADJGHEIQSXMKKRBJ08H - key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs # Using a profile from pillars Ensure myelasticache exists: boto_elasticache.present: - name: myelasticache - engine: redis - cache_node_type: cache.t1.micro - num_cache_nodes: 1 - notification_topic_arn: arn:aws:sns:us-east-1:879879:my-sns-topic - region: us-east-1 - profile: myprofile # Passing in a profile Ensure myelasticache exists: boto_elasticache.present: - name: myelasticache - engine: redis - cache_node_type: cache.t1.micro - num_cache_nodes: 1 - notification_topic_arn: arn:aws:sns:us-east-1:879879:my-sns-topic - region: us-east-1 - profile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto is available. ''' if 'boto_elasticache.exists' in __salt__: return 'boto_elasticache' else: return False def cache_cluster_present(*args, **kwargs): return present(*args, **kwargs) def present( name, engine=None, cache_node_type=None, num_cache_nodes=None, preferred_availability_zone=None, port=None, cache_parameter_group_name=None, cache_security_group_names=None, replication_group_id=None, auto_minor_version_upgrade=True, security_group_ids=None, cache_subnet_group_name=None, engine_version=None, notification_topic_arn=None, preferred_maintenance_window=None, wait=None, region=None, key=None, keyid=None, profile=None): ''' Ensure the cache cluster exists. name Name of the cache cluster (cache cluster id). engine The name of the cache engine to be used for this cache cluster. Valid values are memcached or redis. cache_node_type The compute and memory capacity of the nodes in the cache cluster. cache.t1.micro, cache.m1.small, etc. See: https://boto.readthedocs.io/en/latest/ref/elasticache.html#boto.elasticache.layer1.ElastiCacheConnection.create_cache_cluster num_cache_nodes The number of cache nodes that the cache cluster will have. preferred_availability_zone The EC2 Availability Zone in which the cache cluster will be created. All cache nodes belonging to a cache cluster are placed in the preferred availability zone. port The port number on which each of the cache nodes will accept connections. cache_parameter_group_name The name of the cache parameter group to associate with this cache cluster. If this argument is omitted, the default cache parameter group for the specified engine will be used. cache_security_group_names A list of cache security group names to associate with this cache cluster. Use this parameter only when you are creating a cluster outside of a VPC. replication_group_id The replication group to which this cache cluster should belong. If this parameter is specified, the cache cluster will be added to the specified replication group as a read replica; otherwise, the cache cluster will be a standalone primary that is not part of any replication group. auto_minor_version_upgrade Determines whether minor engine upgrades will be applied automatically to the cache cluster during the maintenance window. A value of True allows these upgrades to occur; False disables automatic upgrades. security_group_ids One or more VPC security groups associated with the cache cluster. Use this parameter only when you are creating a cluster in a VPC. cache_subnet_group_name The name of the cache subnet group to be used for the cache cluster. Use this parameter only when you are creating a cluster in a VPC. engine_version The version number of the cache engine to be used for this cluster. notification_topic_arn The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (SNS) topic to which notifications will be sent. The Amazon SNS topic owner must be the same as the cache cluster owner. preferred_maintenance_window The weekly time range (in UTC) during which system maintenance can occur. Example: sun:05:00-sun:09:00 wait Boolean. Wait for confirmation from boto that the cluster is in the available state. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if cache_security_group_names and cache_subnet_group_name: _subnet_group = __salt__['boto_elasticache.get_cache_subnet_group']( cache_subnet_group_name, region, key, keyid, profile ) vpc_id = _subnet_group['vpc_id'] if not security_group_ids: security_group_ids = [] _security_group_ids = __salt__['boto_secgroup.convert_to_group_ids']( groups=cache_security_group_names, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile ) security_group_ids.extend(_security_group_ids) cache_security_group_names = None config = __salt__['boto_elasticache.get_config'](name, region, key, keyid, profile) if config is None: msg = 'Failed to retrieve cache cluster info from AWS.' ret['comment'] = msg ret['result'] = None return ret elif not config: if __opts__['test']: msg = 'Cache cluster {0} is set to be created.'.format(name) ret['comment'] = msg ret['result'] = None return ret created = __salt__['boto_elasticache.create']( name=name, num_cache_nodes=num_cache_nodes, cache_node_type=cache_node_type, engine=engine, replication_group_id=replication_group_id, engine_version=engine_version, cache_parameter_group_name=cache_parameter_group_name, cache_subnet_group_name=cache_subnet_group_name, cache_security_group_names=cache_security_group_names, security_group_ids=security_group_ids, preferred_availability_zone=preferred_availability_zone, preferred_maintenance_window=preferred_maintenance_window, port=port, notification_topic_arn=notification_topic_arn, auto_minor_version_upgrade=auto_minor_version_upgrade, wait=wait, region=region, key=key, keyid=keyid, profile=profile) if created: ret['changes']['old'] = None config = __salt__['boto_elasticache.get_config'](name, region, key, keyid, profile) ret['changes']['new'] = config else: ret['result'] = False ret['comment'] = 'Failed to create {0} cache cluster.'.format(name) return ret # TODO: support modification of existing elasticache clusters else: ret['comment'] = 'Cache cluster {0} is present.'.format(name) return ret def cache_cluster_absent(*args, **kwargs): return absent(*args, **kwargs) def absent(name, wait=True, region=None, key=None, keyid=None, profile=None): ''' Ensure the named elasticache cluster is deleted. name Name of the cache cluster. wait Boolean. Wait for confirmation from boto that the cluster is in the deleting state. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} is_present = __salt__['boto_elasticache.exists'](name, region, key, keyid, profile) if is_present: if __opts__['test']: ret['comment'] = 'Cache cluster {0} is set to be removed.'.format(name) ret['result'] = None return ret deleted = __salt__['boto_elasticache.delete'](name, wait, region, key, keyid, profile) if deleted: ret['changes']['old'] = name ret['changes']['new'] = None else: ret['result'] = False ret['comment'] = 'Failed to delete {0} cache cluster.'.format(name) else: ret['comment'] = '{0} does not exist in {1}.'.format(name, region) return ret def replication_group_present(*args, **kwargs): return creategroup(*args, **kwargs) def creategroup(name, primary_cluster_id, replication_group_description, wait=None, region=None, key=None, keyid=None, profile=None): ''' Ensure the a replication group is create. name Name of replication group wait Waits for the group to be available primary_cluster_id Name of the master cache node replication_group_description Description for the group region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} is_present = __salt__['boto_elasticache.group_exists'](name, region, key, keyid, profile) if not is_present: if __opts__['test']: ret['comment'] = 'Replication {0} is set to be created.'.format( name) ret['result'] = None created = __salt__['boto_elasticache.create_replication_group'](name, primary_cluster_id, replication_group_description, wait, region, key, keyid, profile) if created: config = __salt__['boto_elasticache.describe_replication_group'](name, region, key, keyid, profile) ret['changes']['old'] = None ret['changes']['new'] = config ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to create {0} replication group.'.format(name) else: ret['comment'] = '{0} replication group exists .'.format(name) ret['result'] = True return ret def subnet_group_absent(name, tags=None, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {} } exists = __salt__['boto_elasticache.subnet_group_exists'](name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not exists: ret['result'] = True ret['comment'] = '{0} ElastiCache subnet group does not exist.'.format(name) return ret if __opts__['test']: ret['comment'] = 'ElastiCache subnet group {0} is set to be removed.'.format(name) ret['result'] = None return ret deleted = __salt__['boto_elasticache.delete_subnet_group'](name, region, key, keyid, profile) if not deleted: ret['result'] = False ret['comment'] = 'Failed to delete {0} ElastiCache subnet group.'.format(name) return ret ret['changes']['old'] = name ret['changes']['new'] = None ret['comment'] = 'ElastiCache subnet group {0} deleted.'.format(name) return ret def replication_group_absent(name, tags=None, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {} } exists = __salt__['boto_elasticache.group_exists'](name=name, region=region, key=key, keyid=keyid, profile=profile) if not exists: ret['result'] = True ret['comment'] = '{0} ElastiCache replication group does not exist.'.format(name) log.info(ret['comment']) return ret if __opts__['test']: ret['comment'] = 'ElastiCache replication group {0} is set to be removed.'.format(name) ret['result'] = True return ret deleted = __salt__['boto_elasticache.delete_replication_group'](name, region, key, keyid, profile) if not deleted: ret['result'] = False log.error(ret['comment']) ret['comment'] = 'Failed to delete {0} ElastiCache replication group.'.format(name) return ret ret['changes']['old'] = name ret['changes']['new'] = None ret['comment'] = 'ElastiCache replication group {0} deleted.'.format(name) log.info(ret['comment']) return ret
saltstack/salt
salt/states/boto_elasticache.py
creategroup
python
def creategroup(name, primary_cluster_id, replication_group_description, wait=None, region=None, key=None, keyid=None, profile=None): ''' Ensure the a replication group is create. name Name of replication group wait Waits for the group to be available primary_cluster_id Name of the master cache node replication_group_description Description for the group region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': None, 'comment': '', 'changes': {}} is_present = __salt__['boto_elasticache.group_exists'](name, region, key, keyid, profile) if not is_present: if __opts__['test']: ret['comment'] = 'Replication {0} is set to be created.'.format( name) ret['result'] = None created = __salt__['boto_elasticache.create_replication_group'](name, primary_cluster_id, replication_group_description, wait, region, key, keyid, profile) if created: config = __salt__['boto_elasticache.describe_replication_group'](name, region, key, keyid, profile) ret['changes']['old'] = None ret['changes']['new'] = config ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to create {0} replication group.'.format(name) else: ret['comment'] = '{0} replication group exists .'.format(name) ret['result'] = True return ret
Ensure the a replication group is create. name Name of replication group wait Waits for the group to be available primary_cluster_id Name of the master cache node replication_group_description Description for the group region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_elasticache.py#L386-L438
null
# -*- coding: utf-8 -*- ''' Manage Elasticache ================== .. versionadded:: 2014.7.0 Create, destroy and update Elasticache clusters. Be aware that this interacts with Amazon's services, and so may incur charges. Note: This module currently only supports creation and deletion of elasticache resources and will not modify clusters when their configuration changes in your state files. This module uses ``boto``, which can be installed via package, or pip. This module accepts explicit elasticache credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More information available `here <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_. If IAM roles are not used you need to specify them either in a pillar file or in the minion's config file: .. code-block:: yaml elasticache.keyid: GKTADJGHEIQSXMKKRBJ08H elasticache.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either passed in as a dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. code-block:: yaml Ensure myelasticache exists: boto_elasticache.present: - name: myelasticache - engine: redis - cache_node_type: cache.t1.micro - num_cache_nodes: 1 - notification_topic_arn: arn:aws:sns:us-east-1:879879:my-sns-topic - region: us-east-1 - keyid: GKTADJGHEIQSXMKKRBJ08H - key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs # Using a profile from pillars Ensure myelasticache exists: boto_elasticache.present: - name: myelasticache - engine: redis - cache_node_type: cache.t1.micro - num_cache_nodes: 1 - notification_topic_arn: arn:aws:sns:us-east-1:879879:my-sns-topic - region: us-east-1 - profile: myprofile # Passing in a profile Ensure myelasticache exists: boto_elasticache.present: - name: myelasticache - engine: redis - cache_node_type: cache.t1.micro - num_cache_nodes: 1 - notification_topic_arn: arn:aws:sns:us-east-1:879879:my-sns-topic - region: us-east-1 - profile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto is available. ''' if 'boto_elasticache.exists' in __salt__: return 'boto_elasticache' else: return False def cache_cluster_present(*args, **kwargs): return present(*args, **kwargs) def present( name, engine=None, cache_node_type=None, num_cache_nodes=None, preferred_availability_zone=None, port=None, cache_parameter_group_name=None, cache_security_group_names=None, replication_group_id=None, auto_minor_version_upgrade=True, security_group_ids=None, cache_subnet_group_name=None, engine_version=None, notification_topic_arn=None, preferred_maintenance_window=None, wait=None, region=None, key=None, keyid=None, profile=None): ''' Ensure the cache cluster exists. name Name of the cache cluster (cache cluster id). engine The name of the cache engine to be used for this cache cluster. Valid values are memcached or redis. cache_node_type The compute and memory capacity of the nodes in the cache cluster. cache.t1.micro, cache.m1.small, etc. See: https://boto.readthedocs.io/en/latest/ref/elasticache.html#boto.elasticache.layer1.ElastiCacheConnection.create_cache_cluster num_cache_nodes The number of cache nodes that the cache cluster will have. preferred_availability_zone The EC2 Availability Zone in which the cache cluster will be created. All cache nodes belonging to a cache cluster are placed in the preferred availability zone. port The port number on which each of the cache nodes will accept connections. cache_parameter_group_name The name of the cache parameter group to associate with this cache cluster. If this argument is omitted, the default cache parameter group for the specified engine will be used. cache_security_group_names A list of cache security group names to associate with this cache cluster. Use this parameter only when you are creating a cluster outside of a VPC. replication_group_id The replication group to which this cache cluster should belong. If this parameter is specified, the cache cluster will be added to the specified replication group as a read replica; otherwise, the cache cluster will be a standalone primary that is not part of any replication group. auto_minor_version_upgrade Determines whether minor engine upgrades will be applied automatically to the cache cluster during the maintenance window. A value of True allows these upgrades to occur; False disables automatic upgrades. security_group_ids One or more VPC security groups associated with the cache cluster. Use this parameter only when you are creating a cluster in a VPC. cache_subnet_group_name The name of the cache subnet group to be used for the cache cluster. Use this parameter only when you are creating a cluster in a VPC. engine_version The version number of the cache engine to be used for this cluster. notification_topic_arn The Amazon Resource Name (ARN) of the Amazon Simple Notification Service (SNS) topic to which notifications will be sent. The Amazon SNS topic owner must be the same as the cache cluster owner. preferred_maintenance_window The weekly time range (in UTC) during which system maintenance can occur. Example: sun:05:00-sun:09:00 wait Boolean. Wait for confirmation from boto that the cluster is in the available state. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if cache_security_group_names and cache_subnet_group_name: _subnet_group = __salt__['boto_elasticache.get_cache_subnet_group']( cache_subnet_group_name, region, key, keyid, profile ) vpc_id = _subnet_group['vpc_id'] if not security_group_ids: security_group_ids = [] _security_group_ids = __salt__['boto_secgroup.convert_to_group_ids']( groups=cache_security_group_names, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile ) security_group_ids.extend(_security_group_ids) cache_security_group_names = None config = __salt__['boto_elasticache.get_config'](name, region, key, keyid, profile) if config is None: msg = 'Failed to retrieve cache cluster info from AWS.' ret['comment'] = msg ret['result'] = None return ret elif not config: if __opts__['test']: msg = 'Cache cluster {0} is set to be created.'.format(name) ret['comment'] = msg ret['result'] = None return ret created = __salt__['boto_elasticache.create']( name=name, num_cache_nodes=num_cache_nodes, cache_node_type=cache_node_type, engine=engine, replication_group_id=replication_group_id, engine_version=engine_version, cache_parameter_group_name=cache_parameter_group_name, cache_subnet_group_name=cache_subnet_group_name, cache_security_group_names=cache_security_group_names, security_group_ids=security_group_ids, preferred_availability_zone=preferred_availability_zone, preferred_maintenance_window=preferred_maintenance_window, port=port, notification_topic_arn=notification_topic_arn, auto_minor_version_upgrade=auto_minor_version_upgrade, wait=wait, region=region, key=key, keyid=keyid, profile=profile) if created: ret['changes']['old'] = None config = __salt__['boto_elasticache.get_config'](name, region, key, keyid, profile) ret['changes']['new'] = config else: ret['result'] = False ret['comment'] = 'Failed to create {0} cache cluster.'.format(name) return ret # TODO: support modification of existing elasticache clusters else: ret['comment'] = 'Cache cluster {0} is present.'.format(name) return ret def subnet_group_present(name, subnet_ids=None, subnet_names=None, description=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Ensure ElastiCache subnet group exists. .. versionadded:: 2015.8.0 name The name for the ElastiCache subnet group. This value is stored as a lowercase string. subnet_ids A list of VPC subnet IDs for the cache subnet group. Exclusive with subnet_names. subnet_names A list of VPC subnet names for the cache subnet group. Exclusive with subnet_ids. description Subnet group description. tags A list of tags. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {} } exists = __salt__['boto_elasticache.subnet_group_exists'](name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not exists: if __opts__['test']: ret['comment'] = 'Subnet group {0} is set to be created.'.format(name) ret['result'] = None return ret created = __salt__['boto_elasticache.create_subnet_group'](name=name, subnet_ids=subnet_ids, subnet_names=subnet_names, description=description, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not created: ret['result'] = False ret['comment'] = 'Failed to create {0} subnet group.'.format(name) return ret ret['changes']['old'] = None ret['changes']['new'] = name ret['comment'] = 'Subnet group {0} created.'.format(name) return ret ret['comment'] = 'Subnet group present.' return ret def cache_cluster_absent(*args, **kwargs): return absent(*args, **kwargs) def absent(name, wait=True, region=None, key=None, keyid=None, profile=None): ''' Ensure the named elasticache cluster is deleted. name Name of the cache cluster. wait Boolean. Wait for confirmation from boto that the cluster is in the deleting state. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} is_present = __salt__['boto_elasticache.exists'](name, region, key, keyid, profile) if is_present: if __opts__['test']: ret['comment'] = 'Cache cluster {0} is set to be removed.'.format(name) ret['result'] = None return ret deleted = __salt__['boto_elasticache.delete'](name, wait, region, key, keyid, profile) if deleted: ret['changes']['old'] = name ret['changes']['new'] = None else: ret['result'] = False ret['comment'] = 'Failed to delete {0} cache cluster.'.format(name) else: ret['comment'] = '{0} does not exist in {1}.'.format(name, region) return ret def replication_group_present(*args, **kwargs): return creategroup(*args, **kwargs) def subnet_group_absent(name, tags=None, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {} } exists = __salt__['boto_elasticache.subnet_group_exists'](name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not exists: ret['result'] = True ret['comment'] = '{0} ElastiCache subnet group does not exist.'.format(name) return ret if __opts__['test']: ret['comment'] = 'ElastiCache subnet group {0} is set to be removed.'.format(name) ret['result'] = None return ret deleted = __salt__['boto_elasticache.delete_subnet_group'](name, region, key, keyid, profile) if not deleted: ret['result'] = False ret['comment'] = 'Failed to delete {0} ElastiCache subnet group.'.format(name) return ret ret['changes']['old'] = name ret['changes']['new'] = None ret['comment'] = 'ElastiCache subnet group {0} deleted.'.format(name) return ret def replication_group_absent(name, tags=None, region=None, key=None, keyid=None, profile=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {} } exists = __salt__['boto_elasticache.group_exists'](name=name, region=region, key=key, keyid=keyid, profile=profile) if not exists: ret['result'] = True ret['comment'] = '{0} ElastiCache replication group does not exist.'.format(name) log.info(ret['comment']) return ret if __opts__['test']: ret['comment'] = 'ElastiCache replication group {0} is set to be removed.'.format(name) ret['result'] = True return ret deleted = __salt__['boto_elasticache.delete_replication_group'](name, region, key, keyid, profile) if not deleted: ret['result'] = False log.error(ret['comment']) ret['comment'] = 'Failed to delete {0} ElastiCache replication group.'.format(name) return ret ret['changes']['old'] = name ret['changes']['new'] = None ret['comment'] = 'ElastiCache replication group {0} deleted.'.format(name) log.info(ret['comment']) return ret
saltstack/salt
salt/states/statuspage.py
_clear_dict
python
def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None )
Eliminates None entries from the features of the endpoint dict.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L85-L93
null
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
_ignore_keys
python
def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS )
Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L96-L105
null
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
_unique
python
def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list
Returns an unique list of dictionaries given a list that may contain duplicates.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L108-L116
null
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
_clear_ignore
python
def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None )
Both _clear_dict and _ignore_keys in a single iteration.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L119-L127
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
_find_match
python
def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele
Find a matching element in a list.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L140-L147
null
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
_update_on_fields
python
def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update
Return a dict with fields that differ between two dicts.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L150-L165
null
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
_compute_diff
python
def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints }
Compares configured endpoints with the expected configuration and returns the differences.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L168-L218
null
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
create
python
def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out')
Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L225-L286
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _default_ret(name):\n '''\n Default dictionary returned.\n '''\n return {\n 'name': name,\n 'result': False,\n 'comment': '',\n 'changes': {}\n }\n" ]
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
update
python
def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out')
Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L289-L356
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _default_ret(name):\n '''\n Default dictionary returned.\n '''\n return {\n 'name': name,\n 'result': False,\n 'comment': '',\n 'changes': {}\n }\n" ]
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
delete
python
def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True
Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L359-L414
[ "def _default_ret(name):\n '''\n Default dictionary returned.\n '''\n return {\n 'name': name,\n 'result': False,\n 'comment': '',\n 'changes': {}\n }\n" ]
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
saltstack/salt
salt/states/statuspage.py
managed
python
def managed(name, config, api_url=None, page_id=None, api_key=None, api_version=None, pace=_PACE, allow_empty=False): ''' Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor ''' complete_diff = {} ret = _default_ret(name) if not config and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret is_empty = True for endpoint_name, endpoint_expected_config in six.iteritems(config): if endpoint_expected_config: is_empty = False endpoint_existing_config_ret = __salt__['statuspage.retrieve'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not endpoint_existing_config_ret.get('result'): ret.update({ 'comment': endpoint_existing_config_ret.get('comment') }) return ret # stop at first error endpoint_existing_config = endpoint_existing_config_ret.get('out') complete_diff[endpoint_name] = _compute_diff(endpoint_expected_config, endpoint_existing_config) if is_empty and not allow_empty: ret.update({ 'result': False, 'comment': 'Cannot remove everything. To allow this, please set the option `allow_empty` as True.' }) return ret any_changes = False for endpoint_name, endpoint_diff in six.iteritems(complete_diff): if endpoint_diff.get('add') or endpoint_diff.get('update') or endpoint_diff.get('remove'): any_changes = True if not any_changes: ret.update({ 'result': True, 'comment': 'No changes required.', 'changes': {} }) return ret ret.update({ 'changes': complete_diff }) if __opts__.get('test'): ret.update({ 'comment': 'Testing mode. Would apply the following changes:', 'result': None }) return ret for endpoint_name, endpoint_diff in six.iteritems(complete_diff): endpoint_sg = endpoint_name[:-1] # singular for new_endpoint in endpoint_diff.get('add'): log.debug('Defining new %s %s', endpoint_sg, new_endpoint ) adding = __salt__['statuspage.create'](endpoint=endpoint_name, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **new_endpoint) if not adding.get('result'): ret.update({ 'comment': adding.get('comment') }) return ret if pace: time.sleep(1/pace) for update_endpoint in endpoint_diff.get('update'): if 'id' not in update_endpoint: continue endpoint_id = update_endpoint.pop('id') log.debug('Updating %s #%s: %s', endpoint_sg, endpoint_id, update_endpoint ) updating = __salt__['statuspage.update'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **update_endpoint) if not updating.get('result'): ret.update({ 'comment': updating.get('comment') }) return ret if pace: time.sleep(1/pace) for remove_endpoint in endpoint_diff.get('remove'): if 'id' not in remove_endpoint: continue endpoint_id = remove_endpoint.pop('id') log.debug('Removing %s #%s', endpoint_sg, endpoint_id ) removing = __salt__['statuspage.delete'](endpoint=endpoint_name, id=endpoint_id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not removing.get('result'): ret.update({ 'comment': removing.get('comment') }) return ret if pace: time.sleep(1/pace) ret.update({ 'result': True, 'comment': 'StatusPage updated.' }) return ret
Manage the StatusPage configuration. config Dictionary with the expected configuration of the StatusPage. The main level keys of this dictionary represent the endpoint name. If a certain endpoint does not exist in this structure, it will be ignored / not configured. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. pace: 1 Max requests per second allowed by the API. allow_empty: False Allow empty config. SLS example: .. code-block:: yaml my-statuspage-config: statuspage.managed: - config: components: - name: component1 group_id: uy4g37rf - name: component2 group_id: 3n4uyu4gf incidents: - name: incident1 status: resolved impact: major backfilled: false - name: incident2 status: investigating impact: minor
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L417-L590
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _default_ret(name):\n '''\n Default dictionary returned.\n '''\n return {\n 'name': name,\n 'result': False,\n 'comment': '',\n 'changes': {}\n }\n", "def _compute_diff(expected_endpoints, configured_endpoints):\n '''\n Compares configured endpoints with the expected configuration and returns the differences.\n '''\n new_endpoints = []\n update_endpoints = []\n remove_endpoints = []\n\n ret = _compute_diff_ret()\n\n # noth configured => configure with expected endpoints\n if not configured_endpoints:\n ret.update({\n 'add': expected_endpoints\n })\n return ret\n\n # noting expected => remove everything\n if not expected_endpoints:\n ret.update({\n 'remove': configured_endpoints\n })\n return ret\n\n expected_endpoints_clear = _clear_ignore_list(expected_endpoints)\n configured_endpoints_clear = _clear_ignore_list(configured_endpoints)\n\n for expected_endpoint_clear in expected_endpoints_clear:\n if expected_endpoint_clear not in configured_endpoints_clear:\n # none equal => add or update\n matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear)\n if not matching_ele:\n # new element => add\n new_endpoints.append(expected_endpoint_clear)\n else:\n # element matched, but some fields are different\n update_fields = _update_on_fields(matching_ele, expected_endpoint_clear)\n if update_fields:\n update_endpoints.append(update_fields)\n for configured_endpoint_clear in configured_endpoints_clear:\n if configured_endpoint_clear not in expected_endpoints_clear:\n matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear)\n if not matching_ele:\n # no match found => remove\n remove_endpoints.append(configured_endpoint_clear)\n\n return {\n 'add': new_endpoints,\n 'update': update_endpoints,\n 'remove': remove_endpoints\n }\n" ]
# -*- coding: utf-8 -*- ''' StatusPage ========== Manage the StatusPage_ configuration. .. _StatusPage: https://www.statuspage.io/ In the minion configuration file, the following block is required: .. code-block:: yaml statuspage: api_key: <API_KEY> page_id: <PAGE_ID> .. versionadded:: 2017.7.0 ''' from __future__ import absolute_import, unicode_literals, print_function # import python std lib import time import logging # import salt from salt.ext import six # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- __virtualname__ = 'statuspage' log = logging.getLogger(__file__) _DO_NOT_COMPARE_FIELDS = [ 'created_at', 'updated_at' ] _MATCH_KEYS = [ 'id', 'name' ] _PACE = 1 # 1 request per second # ---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- def __virtual__(): ''' Return the execution module virtualname. ''' return __virtualname__ def _default_ret(name): ''' Default dictionary returned. ''' return { 'name': name, 'result': False, 'comment': '', 'changes': {} } def _compute_diff_ret(): ''' Default dictionary retuned by the _compute_diff helper. ''' return { 'add': [], 'update': [], 'remove': [] } def _clear_dict(endpoint_props): ''' Eliminates None entries from the features of the endpoint dict. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_val is not None ) def _ignore_keys(endpoint_props): ''' Ignores some keys that might be different without any important info. These keys are defined under _DO_NOT_COMPARE_FIELDS. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS ) def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list def _clear_ignore(endpoint_props): ''' Both _clear_dict and _ignore_keys in a single iteration. ''' return dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(endpoint_props) if prop_name not in _DO_NOT_COMPARE_FIELDS and prop_val is not None ) def _clear_ignore_list(lst): ''' Apply _clear_ignore to a list. ''' return _unique([ _clear_ignore(ele) for ele in lst ]) def _find_match(ele, lst): ''' Find a matching element in a list. ''' for _ele in lst: for match_key in _MATCH_KEYS: if _ele.get(match_key) == ele.get(match_key): return ele def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEYS ) if len(set(fields_update.keys()) | set(_MATCH_KEYS)) > len(set(_MATCH_KEYS)): if 'id' not in fields_update: # in case of update, the ID is necessary # if not specified in the pillar, # will try to get it from the prev_ele fields_update['id'] = prev_ele['id'] return fields_update def _compute_diff(expected_endpoints, configured_endpoints): ''' Compares configured endpoints with the expected configuration and returns the differences. ''' new_endpoints = [] update_endpoints = [] remove_endpoints = [] ret = _compute_diff_ret() # noth configured => configure with expected endpoints if not configured_endpoints: ret.update({ 'add': expected_endpoints }) return ret # noting expected => remove everything if not expected_endpoints: ret.update({ 'remove': configured_endpoints }) return ret expected_endpoints_clear = _clear_ignore_list(expected_endpoints) configured_endpoints_clear = _clear_ignore_list(configured_endpoints) for expected_endpoint_clear in expected_endpoints_clear: if expected_endpoint_clear not in configured_endpoints_clear: # none equal => add or update matching_ele = _find_match(expected_endpoint_clear, configured_endpoints_clear) if not matching_ele: # new element => add new_endpoints.append(expected_endpoint_clear) else: # element matched, but some fields are different update_fields = _update_on_fields(matching_ele, expected_endpoint_clear) if update_fields: update_endpoints.append(update_fields) for configured_endpoint_clear in configured_endpoints_clear: if configured_endpoint_clear not in expected_endpoints_clear: matching_ele = _find_match(configured_endpoint_clear, expected_endpoints_clear) if not matching_ele: # no match found => remove remove_endpoints.append(configured_endpoint_clear) return { 'add': new_endpoints, 'update': update_endpoints, 'remove': remove_endpoints } # ---------------------------------------------------------------------------------------------------------------------- # callable functions # ---------------------------------------------------------------------------------------------------------------------- def create(name, endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Insert a new entry under a specific endpoint. endpoint: incidents Insert under this specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. kwargs Other params. SLS Example: .. code-block:: yaml create-my-component: statuspage.create: - endpoint: components - name: my component - group_id: 993vgplshj12 ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if __opts__['test']: ret['comment'] = 'The following {endpoint} would be created:'.format(endpoint=endpoint_sg) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_create = __salt__['statuspage.create'](endpoint=endpoint, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_create.get('result'): ret['comment'] = 'Unable to create {endpoint}: {msg}'.format(endpoint=endpoint_sg, msg=sp_create.get('comment')) else: ret['comment'] = '{endpoint} created!'.format(endpoint=endpoint_sg) ret['result'] = True ret['changes'] = sp_create.get('out') def update(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None, **kwargs): ''' Update attribute(s) of a specific endpoint. id The unique ID of the enpoint entry. endpoint: incidents Endpoint name. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml update-my-incident: statuspage.update: - id: dz959yz2nd4l - status: resolved ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be updated:'.format(endpoint=endpoint_sg, id=id) ret['result'] = None ret['changes'][endpoint] = {} for karg, warg in six.iteritems(kwargs): if warg is None or karg.startswith('__'): continue ret['changes'][endpoint][karg] = warg return ret sp_update = __salt__['statuspage.update'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version, **kwargs) if not sp_update.get('result'): ret['comment'] = 'Unable to update {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_update.get('comment')) else: ret['comment'] = '{endpoint} #{id} updated!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True ret['changes'] = sp_update.get('out') def delete(name, endpoint='incidents', id=None, api_url=None, page_id=None, api_key=None, api_version=None): ''' Remove an entry from an endpoint. endpoint: incidents Request a specific endpoint. page_id Page ID. Can also be specified in the config file. api_key API key. Can also be specified in the config file. api_version: 1 API version. Can also be specified in the config file. api_url Custom API URL in case the user has a StatusPage service running in a custom environment. SLS Example: .. code-block:: yaml delete-my-component: statuspage.delete: - endpoint: components - id: ftgks51sfs2d ''' ret = _default_ret(name) endpoint_sg = endpoint[:-1] # singular if not id: log.error('Invalid %s ID', endpoint_sg) ret['comment'] = 'Please specify a valid {endpoint} ID'.format(endpoint=endpoint_sg) return ret if __opts__['test']: ret['comment'] = '{endpoint} #{id} would be removed!'.format(endpoint=endpoint_sg, id=id) ret['result'] = None sp_delete = __salt__['statuspage.delete'](endpoint=endpoint, id=id, api_url=api_url, page_id=page_id, api_key=api_key, api_version=api_version) if not sp_delete.get('result'): ret['comment'] = 'Unable to delete {endpoint} #{id}: {msg}'.format(endpoint=endpoint_sg, id=id, msg=sp_delete.get('comment')) else: ret['comment'] = '{endpoint} #{id} deleted!'.format(endpoint=endpoint_sg, id=id) ret['result'] = True
saltstack/salt
salt/states/splunk.py
present
python
def present(email, profile="splunk", **kwargs): ''' Ensure a user is present .. code-block:: yaml ensure example test user 1: splunk.user_present: - realname: 'Example TestUser1' - name: 'exampleuser' - email: 'example@domain.com' - roles: ['user'] The following parameters are required: email This is the email of the user in splunk ''' name = kwargs.get('name') ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['splunk.get_user'](email, profile=profile, user_details=True) if not target: if __opts__['test']: ret['comment'] = 'User {0} will be created'.format(name) return ret # create the user result = __salt__['splunk.create_user']( email, profile=profile, **kwargs ) if result: ret['changes'].setdefault('old', None) ret['changes'].setdefault('new', 'User {0} exists'.format(name)) ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to create {0}'.format(name) return ret else: ret['comment'] = 'User {0} set to be updated.'.format(name) if __opts__['test']: ret['result'] = None return ret # found a user... updating result = __salt__['splunk.update_user']( email, profile, **kwargs ) if isinstance(result, bool) and result: # no update ret['result'] = None ret['comment'] = "No changes" else: diff = {} for field in ['name', 'realname', 'roles', 'defaultApp', 'tz', 'capabilities']: if field == 'roles': diff['roles'] = list(set(target.get(field, [])).symmetric_difference(set(result.get(field, [])))) elif target.get(field) != result.get(field): diff[field] = result.get(field) newvalues = result ret['result'] = True ret['changes']['diff'] = diff ret['changes']['old'] = target ret['changes']['new'] = newvalues return ret
Ensure a user is present .. code-block:: yaml ensure example test user 1: splunk.user_present: - realname: 'Example TestUser1' - name: 'exampleuser' - email: 'example@domain.com' - roles: ['user'] The following parameters are required: email This is the email of the user in splunk
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/splunk.py#L26-L103
null
# -*- coding: utf-8 -*- ''' Splunk User State Module .. versionadded:: 2016.3.0. This state is used to ensure presence of users in splunk. .. code-block:: yaml ensure example test user 1: splunk.present: - name: 'Example TestUser1' - email: example@domain.com ''' from __future__ import absolute_import, unicode_literals, print_function def __virtual__(): ''' Only load if the splunk module is available in __salt__ ''' return 'splunk' if 'splunk.list_users' in __salt__ else False def absent(email, profile="splunk", **kwargs): ''' Ensure a splunk user is absent .. code-block:: yaml ensure example test user 1: splunk.absent: - email: 'example@domain.com' - name: 'exampleuser' The following parameters are required: email This is the email of the user in splunk name This is the splunk username used to identify the user. ''' user_identity = kwargs.get('name') ret = { 'name': user_identity, 'changes': {}, 'result': None, 'comment': 'User {0} is absent.'.format(user_identity) } target = __salt__['splunk.get_user'](email, profile=profile) if not target: ret['comment'] = 'User {0} does not exist'.format(user_identity) ret['result'] = True return ret if __opts__['test']: ret['comment'] = "User {0} is all set to be deleted".format(user_identity) ret['result'] = None return ret result = __salt__['splunk.delete_user'](email, profile=profile) if result: ret['comment'] = 'Deleted user {0}'.format(user_identity) ret['changes'].setdefault('old', 'User {0} exists'.format(user_identity)) ret['changes'].setdefault('new', 'User {0} deleted'.format(user_identity)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(user_identity) ret['result'] = False return ret
saltstack/salt
salt/states/splunk.py
absent
python
def absent(email, profile="splunk", **kwargs): ''' Ensure a splunk user is absent .. code-block:: yaml ensure example test user 1: splunk.absent: - email: 'example@domain.com' - name: 'exampleuser' The following parameters are required: email This is the email of the user in splunk name This is the splunk username used to identify the user. ''' user_identity = kwargs.get('name') ret = { 'name': user_identity, 'changes': {}, 'result': None, 'comment': 'User {0} is absent.'.format(user_identity) } target = __salt__['splunk.get_user'](email, profile=profile) if not target: ret['comment'] = 'User {0} does not exist'.format(user_identity) ret['result'] = True return ret if __opts__['test']: ret['comment'] = "User {0} is all set to be deleted".format(user_identity) ret['result'] = None return ret result = __salt__['splunk.delete_user'](email, profile=profile) if result: ret['comment'] = 'Deleted user {0}'.format(user_identity) ret['changes'].setdefault('old', 'User {0} exists'.format(user_identity)) ret['changes'].setdefault('new', 'User {0} deleted'.format(user_identity)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(user_identity) ret['result'] = False return ret
Ensure a splunk user is absent .. code-block:: yaml ensure example test user 1: splunk.absent: - email: 'example@domain.com' - name: 'exampleuser' The following parameters are required: email This is the email of the user in splunk name This is the splunk username used to identify the user.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/splunk.py#L106-L158
null
# -*- coding: utf-8 -*- ''' Splunk User State Module .. versionadded:: 2016.3.0. This state is used to ensure presence of users in splunk. .. code-block:: yaml ensure example test user 1: splunk.present: - name: 'Example TestUser1' - email: example@domain.com ''' from __future__ import absolute_import, unicode_literals, print_function def __virtual__(): ''' Only load if the splunk module is available in __salt__ ''' return 'splunk' if 'splunk.list_users' in __salt__ else False def present(email, profile="splunk", **kwargs): ''' Ensure a user is present .. code-block:: yaml ensure example test user 1: splunk.user_present: - realname: 'Example TestUser1' - name: 'exampleuser' - email: 'example@domain.com' - roles: ['user'] The following parameters are required: email This is the email of the user in splunk ''' name = kwargs.get('name') ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['splunk.get_user'](email, profile=profile, user_details=True) if not target: if __opts__['test']: ret['comment'] = 'User {0} will be created'.format(name) return ret # create the user result = __salt__['splunk.create_user']( email, profile=profile, **kwargs ) if result: ret['changes'].setdefault('old', None) ret['changes'].setdefault('new', 'User {0} exists'.format(name)) ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to create {0}'.format(name) return ret else: ret['comment'] = 'User {0} set to be updated.'.format(name) if __opts__['test']: ret['result'] = None return ret # found a user... updating result = __salt__['splunk.update_user']( email, profile, **kwargs ) if isinstance(result, bool) and result: # no update ret['result'] = None ret['comment'] = "No changes" else: diff = {} for field in ['name', 'realname', 'roles', 'defaultApp', 'tz', 'capabilities']: if field == 'roles': diff['roles'] = list(set(target.get(field, [])).symmetric_difference(set(result.get(field, [])))) elif target.get(field) != result.get(field): diff[field] = result.get(field) newvalues = result ret['result'] = True ret['changes']['diff'] = diff ret['changes']['old'] = target ret['changes']['new'] = newvalues return ret
saltstack/salt
salt/states/keyboard.py
system
python
def system(name): ''' Set the keyboard layout for the system name The keyboard layout to use ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __salt__['keyboard.get_sys']() == name: ret['result'] = True ret['comment'] = 'System layout {0} already set'.format(name) return ret if __opts__['test']: ret['comment'] = 'System layout {0} needs to be set'.format(name) return ret if __salt__['keyboard.set_sys'](name): ret['changes'] = {'layout': name} ret['result'] = True ret['comment'] = 'Set system keyboard layout {0}'.format(name) return ret else: ret['result'] = False ret['comment'] = 'Failed to set system keyboard layout' return ret
Set the keyboard layout for the system name The keyboard layout to use
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keyboard.py#L32-L58
null
# -*- coding: utf-8 -*- ''' Management of keyboard layouts ============================== The keyboard layout can be managed for the system: .. code-block:: yaml us: keyboard.system Or it can be managed for XOrg: .. code-block:: yaml us: keyboard.xorg ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the keyboard module is available in __salt__ ''' return 'keyboard.get_sys' in __salt__ def xorg(name): ''' Set the keyboard layout for XOrg layout The keyboard layout to use ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __salt__['keyboard.get_x']() == name: ret['result'] = True ret['comment'] = 'XOrg layout {0} already set'.format(name) return ret if __opts__['test']: ret['comment'] = 'XOrg layout {0} needs to be set'.format(name) return ret if __salt__['keyboard.set_x'](name): ret['changes'] = {'layout': name} ret['result'] = True ret['comment'] = 'Set XOrg keyboard layout {0}'.format(name) return ret else: ret['result'] = False ret['comment'] = 'Failed to set XOrg keyboard layout' return ret
saltstack/salt
salt/states/keyboard.py
xorg
python
def xorg(name): ''' Set the keyboard layout for XOrg layout The keyboard layout to use ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __salt__['keyboard.get_x']() == name: ret['result'] = True ret['comment'] = 'XOrg layout {0} already set'.format(name) return ret if __opts__['test']: ret['comment'] = 'XOrg layout {0} needs to be set'.format(name) return ret if __salt__['keyboard.set_x'](name): ret['changes'] = {'layout': name} ret['result'] = True ret['comment'] = 'Set XOrg keyboard layout {0}'.format(name) return ret else: ret['result'] = False ret['comment'] = 'Failed to set XOrg keyboard layout' return ret
Set the keyboard layout for XOrg layout The keyboard layout to use
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keyboard.py#L61-L87
null
# -*- coding: utf-8 -*- ''' Management of keyboard layouts ============================== The keyboard layout can be managed for the system: .. code-block:: yaml us: keyboard.system Or it can be managed for XOrg: .. code-block:: yaml us: keyboard.xorg ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the keyboard module is available in __salt__ ''' return 'keyboard.get_sys' in __salt__ def system(name): ''' Set the keyboard layout for the system name The keyboard layout to use ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __salt__['keyboard.get_sys']() == name: ret['result'] = True ret['comment'] = 'System layout {0} already set'.format(name) return ret if __opts__['test']: ret['comment'] = 'System layout {0} needs to be set'.format(name) return ret if __salt__['keyboard.set_sys'](name): ret['changes'] = {'layout': name} ret['result'] = True ret['comment'] = 'Set system keyboard layout {0}'.format(name) return ret else: ret['result'] = False ret['comment'] = 'Failed to set system keyboard layout' return ret
saltstack/salt
salt/modules/win_service.py
_status_wait
python
def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results
Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L251-L293
null
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
_cmd_quote
python
def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd
r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L296-L317
null
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
get_enabled
python
def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services)
Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L320-L340
[ "def info(name):\n '''\n Get information about a service on the system\n\n Args:\n name (str): The name of the service. This is not the display name. Use\n ``get_service_name`` to find the service name.\n\n Returns:\n dict: A dictionary containing information about the service.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.info spooler\n '''\n try:\n handle_scm = win32service.OpenSCManager(\n None, None, win32service.SC_MANAGER_CONNECT)\n except pywintypes.error as exc:\n raise CommandExecutionError(\n 'Failed to connect to the SCM: {0}'.format(exc.strerror))\n\n try:\n handle_svc = win32service.OpenService(\n handle_scm, name,\n win32service.SERVICE_ENUMERATE_DEPENDENTS |\n win32service.SERVICE_INTERROGATE |\n win32service.SERVICE_QUERY_CONFIG |\n win32service.SERVICE_QUERY_STATUS)\n except pywintypes.error as exc:\n raise CommandExecutionError(\n 'Failed To Open {0}: {1}'.format(name, exc.strerror))\n\n try:\n config_info = win32service.QueryServiceConfig(handle_svc)\n status_info = win32service.QueryServiceStatusEx(handle_svc)\n\n try:\n description = win32service.QueryServiceConfig2(\n handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION)\n except pywintypes.error:\n description = 'Failed to get description'\n\n delayed_start = win32service.QueryServiceConfig2(\n handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO)\n finally:\n win32service.CloseServiceHandle(handle_scm)\n win32service.CloseServiceHandle(handle_svc)\n\n ret = dict()\n try:\n sid = win32security.LookupAccountName(\n '', 'NT Service\\\\{0}'.format(name))[0]\n ret['sid'] = win32security.ConvertSidToStringSid(sid)\n except pywintypes.error:\n ret['sid'] = 'Failed to get SID'\n\n ret['BinaryPath'] = config_info[3]\n ret['LoadOrderGroup'] = config_info[4]\n ret['TagID'] = config_info[5]\n ret['Dependencies'] = config_info[6]\n ret['ServiceAccount'] = config_info[7]\n ret['DisplayName'] = config_info[8]\n ret['Description'] = description\n ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode']\n ret['Status_CheckPoint'] = status_info['CheckPoint']\n ret['Status_WaitHint'] = status_info['WaitHint']\n ret['StartTypeDelayed'] = delayed_start\n\n flags = list()\n for bit in SERVICE_TYPE:\n if isinstance(bit, int):\n if config_info[0] & bit:\n flags.append(SERVICE_TYPE[bit])\n\n ret['ServiceType'] = flags if flags else config_info[0]\n\n flags = list()\n for bit in SERVICE_CONTROLS:\n if status_info['ControlsAccepted'] & bit:\n flags.append(SERVICE_CONTROLS[bit])\n\n ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted']\n\n try:\n ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']]\n except KeyError:\n ret['Status_ExitCode'] = status_info['Win32ExitCode']\n\n try:\n ret['StartType'] = SERVICE_START_TYPE[config_info[1]]\n except KeyError:\n ret['StartType'] = config_info[1]\n\n try:\n ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]]\n except KeyError:\n ret['ErrorControl'] = config_info[2]\n\n try:\n ret['Status'] = SERVICE_STATE[status_info['CurrentState']]\n except KeyError:\n ret['Status'] = status_info['CurrentState']\n\n return ret\n", "def _get_services():\n '''\n Returns a list of all services on the system.\n '''\n handle_scm = win32service.OpenSCManager(\n None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE)\n\n try:\n services = win32service.EnumServicesStatusEx(handle_scm)\n except AttributeError:\n services = win32service.EnumServicesStatus(handle_scm)\n finally:\n win32service.CloseServiceHandle(handle_scm)\n\n return services\n" ]
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
available
python
def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False
Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L366-L386
[ "def get_all():\n '''\n Return all installed services\n\n Returns:\n list: Returns a list of all services on the system.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n '''\n services = _get_services()\n\n ret = set()\n for service in services:\n ret.add(service['ServiceName'])\n\n return sorted(ret)\n" ]
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
_get_services
python
def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services
Returns a list of all services on the system.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L408-L422
null
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
get_all
python
def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret)
Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L425-L444
[ "def _get_services():\n '''\n Returns a list of all services on the system.\n '''\n handle_scm = win32service.OpenSCManager(\n None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE)\n\n try:\n services = win32service.EnumServicesStatusEx(handle_scm)\n except AttributeError:\n services = win32service.EnumServicesStatus(handle_scm)\n finally:\n win32service.CloseServiceHandle(handle_scm)\n\n return services\n" ]
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
get_service_name
python
def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services
The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L447-L482
[ "def _get_services():\n '''\n Returns a list of all services on the system.\n '''\n handle_scm = win32service.OpenSCManager(\n None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE)\n\n try:\n services = win32service.EnumServicesStatusEx(handle_scm)\n except AttributeError:\n services = win32service.EnumServicesStatus(handle_scm)\n finally:\n win32service.CloseServiceHandle(handle_scm)\n\n return services\n" ]
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
info
python
def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret
Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L485-L591
null
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
start
python
def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret
Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L594-L653
[ "def disabled(name):\n '''\n Check to see if the named service is disabled to start on boot\n\n Args:\n name (str): The name of the service to check\n\n Returns:\n bool: True if the service is disabled\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.disabled <service name>\n '''\n return not enabled(name)\n", "def modify(name,\n bin_path=None,\n exe_args=None,\n display_name=None,\n description=None,\n service_type=None,\n start_type=None,\n start_delayed=None,\n error_control=None,\n load_order_group=None,\n dependencies=None,\n account_name=None,\n account_password=None,\n run_interactive=None):\n # pylint: disable=anomalous-backslash-in-string\n '''\n Modify a service's parameters. Changes will not be made for parameters that\n are not passed.\n\n .. versionadded:: 2016.11.0\n\n Args:\n name (str):\n The name of the service. Can be found using the\n ``service.get_service_name`` function\n\n bin_path (str):\n The path to the service executable. Backslashes must be escaped, eg:\n ``C:\\\\path\\\\to\\\\binary.exe``\n\n exe_args (str):\n Any arguments required by the service executable\n\n display_name (str):\n The name to display in the service manager\n\n description (str):\n The description to display for the service\n\n service_type (str):\n Specifies the service type. Default is ``own``. Valid options are as\n follows:\n\n - kernel: Driver service\n - filesystem: File system driver service\n - adapter: Adapter driver service (reserved)\n - recognizer: Recognizer driver service (reserved)\n - own (default): Service runs in its own process\n - share: Service shares a process with one or more other services\n\n start_type (str):\n Specifies the service start type. Valid options are as follows:\n\n - boot: Device driver that is loaded by the boot loader\n - system: Device driver that is started during kernel initialization\n - auto: Service that automatically starts\n - manual: Service must be started manually\n - disabled: Service cannot be started\n\n start_delayed (bool):\n Set the service to Auto(Delayed Start). Only valid if the start_type\n is set to ``Auto``. If service_type is not passed, but the service\n is already set to ``Auto``, then the flag will be set.\n\n error_control (str):\n The severity of the error, and action taken, if this service fails\n to start. Valid options are as follows:\n\n - normal: Error is logged and a message box is displayed\n - severe: Error is logged and computer attempts a restart with the\n last known good configuration\n - critical: Error is logged, computer attempts to restart with the\n last known good configuration, system halts on failure\n - ignore: Error is logged and startup continues, no notification is\n given to the user\n\n load_order_group (str):\n The name of the load order group to which this service belongs\n\n dependencies (list):\n A list of services or load ordering groups that must start before\n this service\n\n account_name (str):\n The name of the account under which the service should run. For\n ``own`` type services this should be in the ``domain\\\\username``\n format. The following are examples of valid built-in service\n accounts:\n\n - NT Authority\\\\LocalService\n - NT Authority\\\\NetworkService\n - NT Authority\\\\LocalSystem\n - .\\LocalSystem\n\n account_password (str):\n The password for the account name specified in ``account_name``. For\n the above built-in accounts, this can be None. Otherwise a password\n must be specified.\n\n run_interactive (bool):\n If this setting is True, the service will be allowed to interact\n with the user. Not recommended for services that run with elevated\n privileges.\n\n Returns:\n dict: a dictionary of changes made\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.modify spooler start_type=disabled\n\n '''\n # pylint: enable=anomalous-backslash-in-string\n # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx\n # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx\n handle_scm = win32service.OpenSCManager(\n None, None, win32service.SC_MANAGER_CONNECT)\n\n try:\n handle_svc = win32service.OpenService(\n handle_scm,\n name,\n win32service.SERVICE_CHANGE_CONFIG |\n win32service.SERVICE_QUERY_CONFIG)\n except pywintypes.error as exc:\n raise CommandExecutionError(\n 'Failed To Open {0}: {1}'.format(name, exc.strerror))\n\n config_info = win32service.QueryServiceConfig(handle_svc)\n\n changes = dict()\n\n # Input Validation\n if bin_path is not None:\n # shlex.quote the path to the binary\n bin_path = _cmd_quote(bin_path)\n if exe_args is not None:\n bin_path = '{0} {1}'.format(bin_path, exe_args)\n changes['BinaryPath'] = bin_path\n\n if service_type is not None:\n if service_type.lower() in SERVICE_TYPE:\n service_type = SERVICE_TYPE[service_type.lower()]\n if run_interactive:\n service_type = service_type | \\\n win32service.SERVICE_INTERACTIVE_PROCESS\n else:\n raise CommandExecutionError(\n 'Invalid Service Type: {0}'.format(service_type))\n else:\n if run_interactive is True:\n service_type = config_info[0] | \\\n win32service.SERVICE_INTERACTIVE_PROCESS\n elif run_interactive is False:\n service_type = config_info[0] ^ \\\n win32service.SERVICE_INTERACTIVE_PROCESS\n else:\n service_type = win32service.SERVICE_NO_CHANGE\n\n if service_type is not win32service.SERVICE_NO_CHANGE:\n flags = list()\n for bit in SERVICE_TYPE:\n if isinstance(bit, int) and service_type & bit:\n flags.append(SERVICE_TYPE[bit])\n\n changes['ServiceType'] = flags if flags else service_type\n\n if start_type is not None:\n if start_type.lower() in SERVICE_START_TYPE:\n start_type = SERVICE_START_TYPE[start_type.lower()]\n else:\n raise CommandExecutionError(\n 'Invalid Start Type: {0}'.format(start_type))\n changes['StartType'] = SERVICE_START_TYPE[start_type]\n else:\n start_type = win32service.SERVICE_NO_CHANGE\n\n if error_control is not None:\n if error_control.lower() in SERVICE_ERROR_CONTROL:\n error_control = SERVICE_ERROR_CONTROL[error_control.lower()]\n else:\n raise CommandExecutionError(\n 'Invalid Error Control: {0}'.format(error_control))\n changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control]\n else:\n error_control = win32service.SERVICE_NO_CHANGE\n\n if account_name is not None:\n changes['ServiceAccount'] = account_name\n if account_name in ['LocalSystem', 'LocalService', 'NetworkService']:\n account_password = ''\n\n if account_password is not None:\n changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX'\n\n if load_order_group is not None:\n changes['LoadOrderGroup'] = load_order_group\n\n if dependencies is not None:\n changes['Dependencies'] = dependencies\n\n if display_name is not None:\n changes['DisplayName'] = display_name\n\n win32service.ChangeServiceConfig(handle_svc,\n service_type,\n start_type,\n error_control,\n bin_path,\n load_order_group,\n 0,\n dependencies,\n account_name,\n account_password,\n display_name)\n\n if description is not None:\n win32service.ChangeServiceConfig2(\n handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description)\n changes['Description'] = description\n\n if start_delayed is not None:\n # You can only set delayed start for services that are set to auto start\n # Start type 2 is Auto\n # Start type -1 is no change\n if (start_type == -1 and config_info[1] == 2) or start_type == 2:\n win32service.ChangeServiceConfig2(\n handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO,\n start_delayed)\n changes['StartTypeDelayed'] = start_delayed\n else:\n changes['Warning'] = 'start_delayed: Requires start_type \"auto\"'\n\n win32service.CloseServiceHandle(handle_scm)\n win32service.CloseServiceHandle(handle_svc)\n\n return changes\n", "def _status_wait(service_name, end_time, service_states):\n '''\n Helper function that will wait for the status of the service to match the\n provided status before an end time expires. Used for service stop and start\n\n .. versionadded:: 2017.7.9,2018.3.4\n\n Args:\n service_name (str):\n The name of the service\n\n end_time (float):\n A future time. e.g. time.time() + 10\n\n service_states (list):\n Services statuses to wait for as returned by info()\n\n Returns:\n dict: A dictionary containing information about the service.\n\n :codeauthor: Damon Atkins <https://github.com/damon-atkins>\n '''\n info_results = info(service_name)\n\n while info_results['Status'] in service_states and time.time() < end_time:\n # From Microsoft: Do not wait longer than the wait hint. A good interval\n # is one-tenth of the wait hint but not less than 1 second and not more\n # than 10 seconds.\n # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service\n # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service\n # Wait hint is in ms\n wait_time = info_results['Status_WaitHint']\n # Convert to seconds or 0\n wait_time = wait_time / 1000 if wait_time else 0\n if wait_time < 1:\n wait_time = 1\n elif wait_time > 10:\n wait_time = 10\n\n time.sleep(wait_time)\n info_results = info(service_name)\n\n return info_results\n", "def start_order(self, with_deps=False, with_parents=False):\n ret = []\n if with_deps:\n ret.extend(self.dependencies(with_indirect=True))\n normalized = self._normalize_name(self._all_services, self._name)\n ret.append(normalized)\n if with_parents:\n ret.extend(self.parents(with_indirect=True))\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
stop
python
def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret
Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L656-L708
[ "def _status_wait(service_name, end_time, service_states):\n '''\n Helper function that will wait for the status of the service to match the\n provided status before an end time expires. Used for service stop and start\n\n .. versionadded:: 2017.7.9,2018.3.4\n\n Args:\n service_name (str):\n The name of the service\n\n end_time (float):\n A future time. e.g. time.time() + 10\n\n service_states (list):\n Services statuses to wait for as returned by info()\n\n Returns:\n dict: A dictionary containing information about the service.\n\n :codeauthor: Damon Atkins <https://github.com/damon-atkins>\n '''\n info_results = info(service_name)\n\n while info_results['Status'] in service_states and time.time() < end_time:\n # From Microsoft: Do not wait longer than the wait hint. A good interval\n # is one-tenth of the wait hint but not less than 1 second and not more\n # than 10 seconds.\n # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service\n # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service\n # Wait hint is in ms\n wait_time = info_results['Status_WaitHint']\n # Convert to seconds or 0\n wait_time = wait_time / 1000 if wait_time else 0\n if wait_time < 1:\n wait_time = 1\n elif wait_time > 10:\n wait_time = 10\n\n time.sleep(wait_time)\n info_results = info(service_name)\n\n return info_results\n", "def stop_order(self, with_deps=False, with_parents=False):\n order = self.start_order(with_deps=with_deps, with_parents=with_parents)\n order.reverse()\n return order\n" ]
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
restart
python
def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret
Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L711-L760
[ "def start(name, timeout=90, with_deps=False, with_parents=False):\n '''\n Start the specified service.\n\n .. warning::\n You cannot start a disabled service in Windows. If the service is\n disabled, it will be changed to ``Manual`` start.\n\n Args:\n name (str): The name of the service to start\n\n timeout (int):\n The time in seconds to wait for the service to start before\n returning. Default is 90 seconds\n\n .. versionadded:: 2017.7.9,2018.3.4\n\n with_deps (bool):\n If enabled start the given service and the services the current\n service depends on.\n\n with_parents (bool):\n If enabled and in case other running services depend on the to be start\n service, this flag indicates that those other services will be started\n as well.\n\n Returns:\n bool: ``True`` if successful, otherwise ``False``. Also returns ``True``\n if the service is already started\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.start <service name>\n '''\n # Set the service to manual if disabled\n if disabled(name):\n modify(name, start_type='Manual')\n\n ret = set()\n\n # Using a list here to maintain order\n services = ServiceDependencies(name, get_all, info)\n start = services.start_order(with_deps=with_deps, with_parents=with_parents)\n log.debug(\"Starting services %s\", start)\n for name in start:\n try:\n win32serviceutil.StartService(name)\n except pywintypes.error as exc:\n if exc.winerror != 1056:\n raise CommandExecutionError(\n 'Failed To Start {0}: {1}'.format(name, exc.strerror))\n log.debug('Service \"%s\" is running', name)\n\n srv_status = _status_wait(service_name=name,\n end_time=time.time() + int(timeout),\n service_states=['Start Pending', 'Stopped'])\n ret.add(srv_status['Status'] == 'Running')\n return False not in ret\n", "def stop(name, timeout=90, with_deps=False, with_parents=False):\n '''\n Stop the specified service\n\n Args:\n name (str): The name of the service to stop\n\n timeout (int):\n The time in seconds to wait for the service to stop before\n returning. Default is 90 seconds\n\n .. versionadded:: 2017.7.9,2018.3.4\n\n with_deps (bool):\n If enabled stop the given service and the services\n the current service depends on.\n\n with_parents (bool):\n If enabled and in case other running services depend on the to be stopped\n service, this flag indicates that those other services will be stopped\n as well.\n If disabled, the service stop will fail in case other running services\n depend on the to be stopped service.\n\n Returns:\n bool: ``True`` if successful, otherwise ``False``. Also returns ``True``\n if the service is already stopped\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.stop <service name>\n '''\n ret = set()\n\n services = ServiceDependencies(name, get_all, info)\n stop = services.stop_order(with_deps=with_deps, with_parents=with_parents)\n log.debug(\"Stopping services %s\", stop)\n for name in stop:\n try:\n win32serviceutil.StopService(name)\n except pywintypes.error as exc:\n if exc.winerror != 1062:\n raise CommandExecutionError(\n 'Failed To Stop {0}: {1}'.format(name, exc.strerror))\n log.debug('Service \"%s\" is not running', name)\n\n srv_status = _status_wait(service_name=name,\n end_time=time.time() + int(timeout),\n service_states=['Running', 'Stop Pending'])\n ret.add(srv_status['Status'] == 'Stopped')\n return False not in ret\n", "def create_win_salt_restart_task():\n '''\n Create a task in Windows task scheduler to enable restarting the salt-minion\n\n Returns:\n bool: ``True`` if successful, otherwise ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.create_win_salt_restart_task()\n '''\n cmd = 'cmd'\n args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \\\n 'salt-minion'\n return __salt__['task.create_task'](name='restart-salt-minion',\n user_name='System',\n force=True,\n action_type='Execute',\n cmd=cmd,\n arguments=args,\n trigger_type='Once',\n start_date='1975-01-01',\n start_time='01:00')\n", "def execute_salt_restart_task():\n '''\n Run the Windows Salt restart task\n\n Returns:\n bool: ``True`` if successful, otherwise ``False``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.execute_salt_restart_task()\n '''\n return __salt__['task.run'](name='restart-salt-minion')\n" ]
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
create_win_salt_restart_task
python
def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00')
Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task()
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L763-L787
null
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name] def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()
saltstack/salt
salt/modules/win_service.py
status
python
def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' results = {} all_services = get_all() contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(all_services, name) else: services = [name] for service in services: results[service] = info(service)['Status'] in ['Running', 'Stop Pending'] if contains_globbing: return results return results[name]
Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_service.py#L806-L840
[ "def info(name):\n '''\n Get information about a service on the system\n\n Args:\n name (str): The name of the service. This is not the display name. Use\n ``get_service_name`` to find the service name.\n\n Returns:\n dict: A dictionary containing information about the service.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.info spooler\n '''\n try:\n handle_scm = win32service.OpenSCManager(\n None, None, win32service.SC_MANAGER_CONNECT)\n except pywintypes.error as exc:\n raise CommandExecutionError(\n 'Failed to connect to the SCM: {0}'.format(exc.strerror))\n\n try:\n handle_svc = win32service.OpenService(\n handle_scm, name,\n win32service.SERVICE_ENUMERATE_DEPENDENTS |\n win32service.SERVICE_INTERROGATE |\n win32service.SERVICE_QUERY_CONFIG |\n win32service.SERVICE_QUERY_STATUS)\n except pywintypes.error as exc:\n raise CommandExecutionError(\n 'Failed To Open {0}: {1}'.format(name, exc.strerror))\n\n try:\n config_info = win32service.QueryServiceConfig(handle_svc)\n status_info = win32service.QueryServiceStatusEx(handle_svc)\n\n try:\n description = win32service.QueryServiceConfig2(\n handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION)\n except pywintypes.error:\n description = 'Failed to get description'\n\n delayed_start = win32service.QueryServiceConfig2(\n handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO)\n finally:\n win32service.CloseServiceHandle(handle_scm)\n win32service.CloseServiceHandle(handle_svc)\n\n ret = dict()\n try:\n sid = win32security.LookupAccountName(\n '', 'NT Service\\\\{0}'.format(name))[0]\n ret['sid'] = win32security.ConvertSidToStringSid(sid)\n except pywintypes.error:\n ret['sid'] = 'Failed to get SID'\n\n ret['BinaryPath'] = config_info[3]\n ret['LoadOrderGroup'] = config_info[4]\n ret['TagID'] = config_info[5]\n ret['Dependencies'] = config_info[6]\n ret['ServiceAccount'] = config_info[7]\n ret['DisplayName'] = config_info[8]\n ret['Description'] = description\n ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode']\n ret['Status_CheckPoint'] = status_info['CheckPoint']\n ret['Status_WaitHint'] = status_info['WaitHint']\n ret['StartTypeDelayed'] = delayed_start\n\n flags = list()\n for bit in SERVICE_TYPE:\n if isinstance(bit, int):\n if config_info[0] & bit:\n flags.append(SERVICE_TYPE[bit])\n\n ret['ServiceType'] = flags if flags else config_info[0]\n\n flags = list()\n for bit in SERVICE_CONTROLS:\n if status_info['ControlsAccepted'] & bit:\n flags.append(SERVICE_CONTROLS[bit])\n\n ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted']\n\n try:\n ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']]\n except KeyError:\n ret['Status_ExitCode'] = status_info['Win32ExitCode']\n\n try:\n ret['StartType'] = SERVICE_START_TYPE[config_info[1]]\n except KeyError:\n ret['StartType'] = config_info[1]\n\n try:\n ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]]\n except KeyError:\n ret['ErrorControl'] = config_info[2]\n\n try:\n ret['Status'] = SERVICE_STATE[status_info['CurrentState']]\n except KeyError:\n ret['Status'] = status_info['CurrentState']\n\n return ret\n", "def get_all():\n '''\n Return all installed services\n\n Returns:\n list: Returns a list of all services on the system.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n '''\n services = _get_services()\n\n ret = set()\n for service in services:\n ret.add(service['ServiceName'])\n\n return sorted(ret)\n" ]
# -*- coding: utf-8 -*- ''' Windows Service module. .. versionchanged:: 2016.11.0 - Rewritten to use PyWin32 ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import fnmatch import logging import re import time # Import Salt libs import salt.utils.platform from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import win32security import win32service import win32serviceutil import pywintypes HAS_WIN32_MODS = True except ImportError: HAS_WIN32_MODS = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' SERVICE_TYPE = {1: 'Kernel Driver', 2: 'File System Driver', 4: 'Adapter Driver', 8: 'Recognizer Driver', 16: 'Win32 Own Process', 32: 'Win32 Share Process', 256: 'Interactive', 'kernel': 1, 'filesystem': 2, 'adapter': 4, 'recognizer': 8, 'own': 16, 'share': 32} SERVICE_CONTROLS = {1: 'Stop', 2: 'Pause/Continue', 4: 'Shutdown', 8: 'Change Parameters', 16: 'Netbind Change', 32: 'Hardware Profile Change', 64: 'Power Event', 128: 'Session Change', 256: 'Pre-Shutdown', 512: 'Time Change', 1024: 'Trigger Event'} SERVICE_STATE = {1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused'} SERVICE_ERRORS = {0: 'No Error', 1066: 'Service Specific Error'} SERVICE_START_TYPE = {'boot': 0, 'system': 1, 'auto': 2, 'manual': 3, 'disabled': 4, 0: 'Boot', 1: 'System', 2: 'Auto', 3: 'Manual', 4: 'Disabled'} SERVICE_ERROR_CONTROL = {0: 'Ignore', 1: 'Normal', 2: 'Severe', 3: 'Critical', 'ignore': 0, 'normal': 1, 'severe': 2, 'critical': 3} def __virtual__(): ''' Only works on Windows systems with PyWin32 installed ''' if not salt.utils.platform.is_windows(): return False, 'Module win_service: module only works on Windows.' if not HAS_WIN32_MODS: return False, 'Module win_service: failed to load win32 modules' return __virtualname__ class ServiceDependencies(object): ''' Helper class which provides functionality to get all dependencies and parents of a Windows service Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. all_services (callback): The name of the method which provides a list of all available service names as done by the ``win_service.get_all()`` method. service_info (callback): The name of the method which allows to pass the service name and returns a dict with meets the requirements ``{service_name: {'Dependencies': []}}`` as done by the ``win_service.info(name)`` method ''' def __init__(self, name, all_services, service_info): # Sort for predictable behavior self._all_services = sorted(all_services()) self._name = self._normalize_name(self._all_services, name) self._service_info = self._populate_service_info(self._all_services, service_info) def _populate_service_info(self, all_services, service_info): ret = {} for name in all_services: dependencies = service_info(name).get('Dependencies', []) # Sort for predictable behavior ret[name] = sorted(self._normalize_multiple_name(all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret[name]) return ret def _dependencies(self, name): dependencies = self._service_info.get(name, []) # Sort for predictable behavior ret = sorted(self._normalize_multiple_name(self._all_services, *dependencies)) log.trace("Added dependencies of %s: %s", name, ret) return ret def _dependencies_recursion(self, name): # Using a list here to maintain order ret = list() try: dependencies = self._dependencies(name) for dependency in dependencies: indirect_dependencies = self._dependencies_recursion(dependency) for indirect_dependency in indirect_dependencies: if indirect_dependency not in ret: ret.append(indirect_dependency) for dependency in dependencies: if dependency not in ret: ret.append(dependency) except Exception as e: log.debug(e) ret = list() return ret def _normalize_name(self, references, difference): # Normalize Input normalized = self._normalize_multiple_name(references, difference) if not normalized: raise ValueError("The provided name '{}' does not exist".format(difference)) return normalized[0] def _normalize_multiple_name(self, references, *differences): # Normalize Input ret = list() for difference in differences: difference_str = str(difference) for reference in references: reference_str = str(reference) if reference_str.lower() == difference_str.lower() and reference_str not in ret: ret.append(reference_str) break return ret def dependencies(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._dependencies_recursion(normalized) else: ret = self._dependencies(normalized) log.trace("Dependencies of '%s': '%s'", normalized, ret) return ret def _parents(self, name): # Using a list here to maintain order ret = list() try: # Sort for predictable behavior for service, dependencies in sorted(self._service_info.items()): if name in dependencies: if service in ret: ret.remove(service) ret.append(service) except Exception as e: log.debug(e) ret = list() return ret def _parents_recursion(self, name): # Using a list here to maintain order ret = list() try: parents = self._parents(name) for parent in parents: if parent not in ret: ret.append(parent) for parent in parents: indirect_parents = self._parents_recursion(parent) for indirect_parent in indirect_parents: if indirect_parent in ret: ret.remove(indirect_parent) ret.append(indirect_parent) except Exception as e: log.debug(e) ret = list() return ret def parents(self, with_indirect=False): normalized = self._normalize_name(self._all_services, self._name) if bool(with_indirect): ret = self._parents_recursion(normalized) else: ret = self._parents(normalized) log.trace("Parents of '%s': '%s'", normalized, ret) return ret def start_order(self, with_deps=False, with_parents=False): ret = [] if with_deps: ret.extend(self.dependencies(with_indirect=True)) normalized = self._normalize_name(self._all_services, self._name) ret.append(normalized) if with_parents: ret.extend(self.parents(with_indirect=True)) return ret def stop_order(self, with_deps=False, with_parents=False): order = self.start_order(with_deps=with_deps, with_parents=with_parents) order.reverse() return order def _status_wait(service_name, end_time, service_states): ''' Helper function that will wait for the status of the service to match the provided status before an end time expires. Used for service stop and start .. versionadded:: 2017.7.9,2018.3.4 Args: service_name (str): The name of the service end_time (float): A future time. e.g. time.time() + 10 service_states (list): Services statuses to wait for as returned by info() Returns: dict: A dictionary containing information about the service. :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' info_results = info(service_name) while info_results['Status'] in service_states and time.time() < end_time: # From Microsoft: Do not wait longer than the wait hint. A good interval # is one-tenth of the wait hint but not less than 1 second and not more # than 10 seconds. # https://docs.microsoft.com/en-us/windows/desktop/services/starting-a-service # https://docs.microsoft.com/en-us/windows/desktop/services/stopping-a-service # Wait hint is in ms wait_time = info_results['Status_WaitHint'] # Convert to seconds or 0 wait_time = wait_time / 1000 if wait_time else 0 if wait_time < 1: wait_time = 1 elif wait_time > 10: wait_time = 10 time.sleep(wait_time) info_results = info(service_name) return info_results def _cmd_quote(cmd): r''' Helper function to properly format the path to the binary for the service Must be wrapped in double quotes to account for paths that have spaces. For example: ``"C:\Program Files\Path\to\bin.exe"`` Args: cmd (str): Full path to the binary Returns: str: Properly quoted path to the binary ''' # Remove all single and double quotes from the beginning and the end pattern = re.compile('^(\\"|\').*|.*(\\"|\')$') while pattern.match(cmd) is not None: cmd = cmd.strip('"').strip('\'') # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path cmd = '"{0}"'.format(cmd) return cmd def get_enabled(): ''' Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Auto']: services.add(service['ServiceName']) return sorted(services) def get_disabled(): ''' Return a list of disabled services. Disabled is defined as a service that is marked 'Disabled' or 'Manual'. Returns: list: A list of disabled services. CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' raw_services = _get_services() services = set() for service in raw_services: if info(service['ServiceName'])['StartType'] in ['Manual', 'Disabled']: services.add(service['ServiceName']) return sorted(services) def available(name): ''' Check if a service is available on the system. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is available, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.available <service name> ''' for service in get_all(): if name.lower() == service.lower(): return True return False def missing(name): ''' The inverse of service.available. Args: name (str): The name of the service to check Returns: bool: ``True`` if the service is missing, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.missing <service name> ''' return name not in get_all() def _get_services(): ''' Returns a list of all services on the system. ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['ServiceName']) return sorted(ret) def get_service_name(*args): ''' The Display Name is what is displayed in Windows when services.msc is executed. Each Display Name has an associated Service Name which is the actual name of the service. This function allows you to discover the Service Name by returning a dictionary of Display Names and Service Names, or filter by adding arguments of Display Names. If no args are passed, return a dict of all services where the keys are the service Display Names and the values are the Service Names. If arguments are passed, create a dict of Display Names and Service Names Returns: dict: A dictionary of display names and service names CLI Examples: .. code-block:: bash salt '*' service.get_service_name salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client' ''' raw_services = _get_services() services = dict() for raw_service in raw_services: if args: if raw_service['DisplayName'] in args or \ raw_service['ServiceName'] in args or \ raw_service['ServiceName'].lower() in args: services[raw_service['DisplayName']] = raw_service['ServiceName'] else: services[raw_service['DisplayName']] = raw_service['ServiceName'] return services def info(name): ''' Get information about a service on the system Args: name (str): The name of the service. This is not the display name. Use ``get_service_name`` to find the service name. Returns: dict: A dictionary containing information about the service. CLI Example: .. code-block:: bash salt '*' service.info spooler ''' try: handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to connect to the SCM: {0}'.format(exc.strerror)) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS | win32service.SERVICE_INTERROGATE | win32service.SERVICE_QUERY_CONFIG | win32service.SERVICE_QUERY_STATUS) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) try: config_info = win32service.QueryServiceConfig(handle_svc) status_info = win32service.QueryServiceStatusEx(handle_svc) try: description = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION) except pywintypes.error: description = 'Failed to get description' delayed_start = win32service.QueryServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO) finally: win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) ret = dict() try: sid = win32security.LookupAccountName( '', 'NT Service\\{0}'.format(name))[0] ret['sid'] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret['sid'] = 'Failed to get SID' ret['BinaryPath'] = config_info[3] ret['LoadOrderGroup'] = config_info[4] ret['TagID'] = config_info[5] ret['Dependencies'] = config_info[6] ret['ServiceAccount'] = config_info[7] ret['DisplayName'] = config_info[8] ret['Description'] = description ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode'] ret['Status_CheckPoint'] = status_info['CheckPoint'] ret['Status_WaitHint'] = status_info['WaitHint'] ret['StartTypeDelayed'] = delayed_start flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int): if config_info[0] & bit: flags.append(SERVICE_TYPE[bit]) ret['ServiceType'] = flags if flags else config_info[0] flags = list() for bit in SERVICE_CONTROLS: if status_info['ControlsAccepted'] & bit: flags.append(SERVICE_CONTROLS[bit]) ret['ControlsAccepted'] = flags if flags else status_info['ControlsAccepted'] try: ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']] except KeyError: ret['Status_ExitCode'] = status_info['Win32ExitCode'] try: ret['StartType'] = SERVICE_START_TYPE[config_info[1]] except KeyError: ret['StartType'] = config_info[1] try: ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]] except KeyError: ret['ErrorControl'] = config_info[2] try: ret['Status'] = SERVICE_STATE[status_info['CurrentState']] except KeyError: ret['Status'] = status_info['CurrentState'] return ret def start(name, timeout=90, with_deps=False, with_parents=False): ''' Start the specified service. .. warning:: You cannot start a disabled service in Windows. If the service is disabled, it will be changed to ``Manual`` start. Args: name (str): The name of the service to start timeout (int): The time in seconds to wait for the service to start before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled start the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be start service, this flag indicates that those other services will be started as well. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already started CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' # Set the service to manual if disabled if disabled(name): modify(name, start_type='Manual') ret = set() # Using a list here to maintain order services = ServiceDependencies(name, get_all, info) start = services.start_order(with_deps=with_deps, with_parents=with_parents) log.debug("Starting services %s", start) for name in start: try: win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: raise CommandExecutionError( 'Failed To Start {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Start Pending', 'Stopped']) ret.add(srv_status['Status'] == 'Running') return False not in ret def stop(name, timeout=90, with_deps=False, with_parents=False): ''' Stop the specified service Args: name (str): The name of the service to stop timeout (int): The time in seconds to wait for the service to stop before returning. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled stop the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be stopped service, this flag indicates that those other services will be stopped as well. If disabled, the service stop will fail in case other running services depend on the to be stopped service. Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is already stopped CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' ret = set() services = ServiceDependencies(name, get_all, info) stop = services.stop_order(with_deps=with_deps, with_parents=with_parents) log.debug("Stopping services %s", stop) for name in stop: try: win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: raise CommandExecutionError( 'Failed To Stop {0}: {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not running', name) srv_status = _status_wait(service_name=name, end_time=time.time() + int(timeout), service_states=['Running', 'Stop Pending']) ret.add(srv_status['Status'] == 'Stopped') return False not in ret def restart(name, timeout=90, with_deps=False, with_parents=False): ''' Restart the named service. This issues a stop command followed by a start. Args: name: The name of the service to restart. .. note:: If the name passed is ``salt-minion`` a scheduled task is created and executed to restart the salt-minion service. timeout (int): The time in seconds to wait for the service to stop and start before returning. Default is 90 seconds .. note:: The timeout is cumulative meaning it is applied to the stop and then to the start command. A timeout of 90 could take up to 180 seconds if the service is long in stopping and starting .. versionadded:: 2017.7.9,2018.3.4 with_deps (bool): If enabled restart the given service and the services the current service depends on. with_parents (bool): If enabled and in case other running services depend on the to be restarted service, this flag indicates that those other services will be restarted as well. If disabled, the service restart will fail in case other running services depend on the to be restarted service. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' if 'salt-minion' in name: create_win_salt_restart_task() return execute_salt_restart_task() ret = set() ret.add(stop(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) ret.add(start(name=name, timeout=timeout, with_deps=with_deps, with_parents=with_parents)) return False not in ret def create_win_salt_restart_task(): ''' Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() ''' cmd = 'cmd' args = '/c ping -n 3 127.0.0.1 && net stop salt-minion && net start ' \ 'salt-minion' return __salt__['task.create_task'](name='restart-salt-minion', user_name='System', force=True, action_type='Execute', cmd=cmd, arguments=args, trigger_type='Once', start_date='1975-01-01', start_time='01:00') def execute_salt_restart_task(): ''' Run the Windows Salt restart task Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.execute_salt_restart_task() ''' return __salt__['task.run'](name='restart-salt-minion') def getsid(name): ''' Return the SID for this windows service Args: name (str): The name of the service for which to return the SID Returns: str: A string representing the SID for the service CLI Example: .. code-block:: bash salt '*' service.getsid <service name> ''' return info(name)['sid'] def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, account_name=None, account_password=None, run_interactive=None): # pylint: disable=anomalous-backslash-in-string ''' Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to the service executable. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any arguments required by the service executable display_name (str): The name to display in the service manager description (str): The description to display for the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal: Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: a dictionary of changes made CLI Example: .. code-block:: bash salt '*' service.modify spooler start_type=disabled ''' # pylint: enable=anomalous-backslash-in-string # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG) except pywintypes.error as exc: raise CommandExecutionError( 'Failed To Open {0}: {1}'.format(name, exc.strerror)) config_info = win32service.QueryServiceConfig(handle_svc) changes = dict() # Input Validation if bin_path is not None: # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) changes['BinaryPath'] = bin_path if service_type is not None: if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) else: if run_interactive is True: service_type = config_info[0] | \ win32service.SERVICE_INTERACTIVE_PROCESS elif run_interactive is False: service_type = config_info[0] ^ \ win32service.SERVICE_INTERACTIVE_PROCESS else: service_type = win32service.SERVICE_NO_CHANGE if service_type is not win32service.SERVICE_NO_CHANGE: flags = list() for bit in SERVICE_TYPE: if isinstance(bit, int) and service_type & bit: flags.append(SERVICE_TYPE[bit]) changes['ServiceType'] = flags if flags else service_type if start_type is not None: if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) changes['StartType'] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE if error_control is not None: if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) changes['ErrorControl'] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE if account_name is not None: changes['ServiceAccount'] = account_name if account_name in ['LocalSystem', 'LocalService', 'NetworkService']: account_password = '' if account_password is not None: changes['ServiceAccountPassword'] = 'XXX-REDACTED-XXX' if load_order_group is not None: changes['LoadOrderGroup'] = load_order_group if dependencies is not None: changes['Dependencies'] = dependencies if display_name is not None: changes['DisplayName'] = display_name win32service.ChangeServiceConfig(handle_svc, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, display_name) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) changes['Description'] = description if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto # Start type -1 is no change if (start_type == -1 and config_info[1] == 2) or start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) changes['StartTypeDelayed'] = start_delayed else: changes['Warning'] = 'start_delayed: Requires start_type "auto"' win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return changes def enable(name, start_type='auto', start_delayed=False, **kwargs): ''' Enable the named service to start at boot Args: name (str): The name of the service to enable. start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual: Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Returns: bool: ``True`` if successful, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' modify(name, start_type=start_type, start_delayed=start_delayed) svcstat = info(name) if start_type.lower() == 'auto': return svcstat['StartType'].lower() == start_type.lower() and svcstat['StartTypeDelayed'] == start_delayed else: return svcstat['StartType'].lower() == start_type.lower() def disable(name, **kwargs): ''' Disable the named service to start at boot Args: name (str): The name of the service to disable Returns: bool: ``True`` if disabled, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' modify(name, start_type='Disabled') return info(name)['StartType'] == 'Disabled' def enabled(name, **kwargs): ''' Check to see if the named service is enabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is set to start CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ''' return info(name)['StartType'] == 'Auto' def disabled(name): ''' Check to see if the named service is disabled to start on boot Args: name (str): The name of the service to check Returns: bool: True if the service is disabled CLI Example: .. code-block:: bash salt '*' service.disabled <service name> ''' return not enabled(name) def create(name, bin_path, exe_args=None, display_name=None, description=None, service_type='own', start_type='manual', start_delayed=False, error_control='normal', load_order_group=None, dependencies=None, account_name='.\\LocalSystem', account_password=None, run_interactive=False, **kwargs): ''' Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' ''' if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError('Service Already Exists: {0}'.format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = '{0} {1}'.format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | \ win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError( 'Invalid Service Type: {0}'.format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError( 'Invalid Start Type: {0}'.format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError( 'Invalid Error Control: {0}'.format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"') if account_name in ['LocalSystem', '.\\LocalSystem', 'LocalService', '.\\LocalService', 'NetworkService', '.\\NetworkService']: account_password = '' # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) # Create the service handle_svc = win32service.CreateService(handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name) def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped before it can be deleted. Default is 90 seconds .. versionadded:: 2017.7.9,2018.3.4 Returns: bool: ``True`` if successful, otherwise ``False``. Also returns ``True`` if the service is not present CLI Example: .. code-block:: bash salt '*' service.delete <service name> ''' handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CONNECT) try: handle_svc = win32service.OpenService( handle_scm, name, win32service.SERVICE_ALL_ACCESS) except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: raise CommandExecutionError( 'Failed to open {0}. {1}'.format(name, exc.strerror)) log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to delete {0}. {1}'.format(name, exc.strerror)) finally: log.debug('Cleaning up') win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) end_time = time.time() + int(timeout) while name in get_all() and time.time() < end_time: time.sleep(1) return name not in get_all()