INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Returns boolean telling whether or not the named service is available
def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl...
Check for modified/updated unit files, and run a daemon-reload if any are found.
def _check_for_unit_changes(name): ''' Check for modified/updated unit files, and run a daemon-reload if any are found. ''' contextkey = 'systemd._check_for_unit_changes.{0}'.format(name) if contextkey not in __context__: if _untracked_custom_unit_found(name) or _unit_file_changed(name):...
Common code for conditionally removing masks before making changes to a service's state.
def _check_unmask(name, unmask, unmask_runtime, root=None): ''' Common code for conditionally removing masks before making changes to a service's state. ''' if unmask: unmask_(name, runtime=False, root=root) if unmask_runtime: unmask_(name, runtime=True, root=root)
Remove context
def _clear_context(): ''' Remove context ''' # Using list() here because modifying a dictionary during iteration will # raise a RuntimeError. for key in list(__context__): try: if key.startswith('systemd._systemctl_status.'): __context__.pop(key) excep...
Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot
def _default_runlevel(): ''' Try to figure out the default runlevel. It is kept in /etc/init/rc-sysinit.conf, but can be overridden with entries in /etc/inittab, or via the kernel command-line at boot ''' # Try to get the "main" default. If this fails, throw up our # hands and just guess "...
Use os.listdir() to get all the unit files
def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS #...
Use os.listdir() and os.access() to get all the initscripts
def _get_sysv_services(root, systemd_services=None): ''' Use os.listdir() and os.access() to get all the initscripts ''' initscript_path = _root(INITSCRIPT_PATH, root) try: sysv_services = os.listdir(initscript_path) except OSError as exc: if exc.errno == errno.ENOENT: ...
Returns the path to the sysv service manager (either update-rc.d or chkconfig)
def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service...
Return the current runlevel
def _runlevel(): ''' Return the current runlevel ''' contextkey = 'systemd._runlevel' if contextkey in __context__: return __context__[contextkey] out = __salt__['cmd.run']('runlevel', python_shell=False, ignore_retcode=True) try: ret = out.split()[1] except IndexError: ...
Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text.
def _strip_scope(msg): ''' Strip unnecessary message about running the command with --scope from stderr so that we can raise an exception with the remaining stderr text. ''' ret = [] for line in msg.splitlines(): if not line.endswith('.scope'): ret.append(line) return '\n...
Build a systemctl command line. Treat unit names without one of the valid suffixes as a service.
def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False, root=None): ''' Build a systemctl command line. Treat unit names without one of the valid suffixes as a service. ''' ret = [] if systemd_scope \ and salt.utils.systemd.has_scope(__context__)...
Helper function which leverages __context__ to keep from running 'systemctl status' more than once.
def _systemctl_status(name): ''' Helper function which leverages __context__ to keep from running 'systemctl status' more than once. ''' contextkey = 'systemd._systemctl_status.%s' % name if contextkey in __context__: return __context__[contextkey] __context__[contextkey] = __salt__[...
A System-V style service is assumed disabled if the "startup" symlink (starts with "S") to its script is found in /etc/init.d in the current runlevel.
def _sysv_enabled(name, root): ''' A System-V style service is assumed disabled if the "startup" symlink (starts with "S") to its script is found in /etc/init.d in the current runlevel. ''' # Find exact match (disambiguate matches like "S01anacron" for cron) rc = _root('/etc/rc{}.d/S*{}'.for...
If the passed service name is not available, but a unit file exist in /etc/systemd/system, return True. Otherwise, return False.
def _untracked_custom_unit_found(name, root=None): ''' If the passed service name is not available, but a unit file exist in /etc/systemd/system, return True. Otherwise, return False. ''' system = _root('/etc/systemd/system', root) unit_path = os.path.join(system, _canonical_unit_name(name)) ...
.. versionadded:: 0.15.0 Reloads systemctl, an action needed whenever unit files are updated. CLI Example: .. code-block:: bash salt '*' service.systemctl_reload
def systemctl_reload(): ''' .. versionadded:: 0.15.0 Reloads systemctl, an action needed whenever unit files are updated. CLI Example: .. code-block:: bash salt '*' service.systemctl_reload ''' out = __salt__['cmd.run_all']( _systemctl_cmd('--system daemon-reload'), ...
Return a list of all running services, so far as systemd is concerned CLI Example: .. code-block:: bash salt '*' service.get_running
def get_running(): ''' Return a list of all running services, so far as systemd is concerned CLI Example: .. code-block:: bash salt '*' service.get_running ''' ret = set() # Get running systemd units out = __salt__['cmd.run']( _systemctl_cmd('--full --no-legend --no-pa...
.. versionadded:: 2015.8.5 Return a list of all static services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_static
def get_static(root=None): ''' .. versionadded:: 2015.8.5 Return a list of all static services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_static ''' ret = set() # Get static systemd u...
Return a list of all available services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_all
def get_all(root=None): ''' Return a list of all available services root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = _get_systemd_services(root) ret.update(set(_get_sysv_services(r...
.. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where t...
def unmask_(name, runtime=False, root=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This i...
.. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where t...
def mask(name, runtime=False, root=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is d...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is r...
def stop(name, no_block=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases wh...
.. versionadded:: 2015.8.0 .. versionchanged:: 2015.8.5 The return data for this function has changed. If the service is masked, the return value will now be the output of the ``systemctl is-enabled`` command (so that a persistent mask can be distinguished from a runtime mask). If th...
def masked(name, runtime=False, root=None): ''' .. versionadded:: 2015.8.0 .. versionchanged:: 2015.8.5 The return data for this function has changed. If the service is masked, the return value will now be the output of the ``systemctl is-enabled`` command (so that a persistent mask ...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is r...
def restart(name, no_block=False, unmask=False, unmask_runtime=False): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is don...
Return the status for a service via systemd. 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 sig (str...
def status(name, sig=None): # pylint: disable=unused-argument ''' Return the status for a service via systemd. 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*``) ...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is r...
def enable(name, no_block=False, unmask=False, unmask_runtime=False, root=None, **kwargs): # pylint: disable=unused-argument ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function fr...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where the ``salt-minion`` service is r...
def disable(name, no_block=False, root=None, **kwargs): # pylint: disable=unused-argument ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's contro...
Return if the named service is enabled to start on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.enabled <service name>
def enabled(name, root=None, **kwargs): # pylint: disable=unused-argument ''' Return if the named service is enabled to start on boot root Enable/disable/mask unit files in the specified root directory CLI Example: .. code-block:: bash salt '*' service.enabled <service name> ...
.. versionadded:: 2014.7.0 Show properties of one or more units/jobs or the manager root Enable/disable/mask unit files in the specified root directory CLI Example: salt '*' service.show <service name>
def show(name, root=None): ''' .. versionadded:: 2014.7.0 Show properties of one or more units/jobs or the manager root Enable/disable/mask unit files in the specified root directory CLI Example: salt '*' service.show <service name> ''' ret = {} out = __salt__['cmd.ru...
.. versionadded:: 2014.7.0 Return a list of all files specified as ``ExecStart`` for all services. root Enable/disable/mask unit files in the specified root directory CLI Example: salt '*' service.execs
def execs(root=None): ''' .. versionadded:: 2014.7.0 Return a list of all files specified as ``ExecStart`` for all services. root Enable/disable/mask unit files in the specified root directory CLI Example: salt '*' service.execs ''' ret = {} for service in get_all(roo...
Manage libvirt keys. name The name variable used to track the execution basepath Defaults to ``/etc/pki``, this is the root location used for libvirt keys on the hypervisor The following parameters are optional: country The country that the certificate should ...
def keys(name, basepath='/etc/pki', **kwargs): ''' Manage libvirt keys. name The name variable used to track the execution basepath Defaults to ``/etc/pki``, this is the root location used for libvirt keys on the hypervisor The following parameters are optional: c...
Helper to call the virt functions. Wildcards supported. :param domain: :param function: :param section: :param comment: :return:
def _virt_call(domain, function, section, comment, connection=None, username=None, password=None, **kwargs): ''' Helper to call the virt functions. Wildcards supported. :param domain: :param function: :param section: :param comment: :return: ''' ret = {'name': domain,...
Stops a VM by shutting it down nicely. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect w...
def stopped(name, connection=None, username=None, password=None): ''' Stops a VM by shutting it down nicely. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults ...
Stops a VM by power off. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overridin...
def powered_off(name, connection=None, username=None, password=None): ''' Stops a VM by power off. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults ....
Starts an existing guest, or defines and starts a new VM with specified arguments. .. versionadded:: 2016.3.0 :param name: name of the virtual machine to run :param cpu: number of CPUs for the virtual machine to create :param mem: amount of memory in MiB for the new virtual machine :param image: d...
def running(name, cpu=None, mem=None, image=None, vm_type=None, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, loader=None, seed=True, install...
Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param passw...
def snapshot(name, suffix=None, connection=None, username=None, password=None): ''' Takes a snapshot of a particular VM or by a UNIX-style wildcard. .. versionadded:: 2016.3.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: userna...
Reboots VMs .. versionadded:: 2016.3.0 :param name: :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, over...
def rebooted(name, connection=None, username=None, password=None): ''' Reboots VMs .. versionadded:: 2016.3.0 :param name: :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults ...
.. deprecated:: 2016.3.0 Reverts to the particular snapshot. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.reverted: - cleanup: True domain_name_1: virt.reverted: - snapshot: snapshot_name - cleanup: False
def reverted(name, snapshot=None, cleanup=False): # pylint: disable=redefined-outer-name ''' .. deprecated:: 2016.3.0 Reverts to the particular snapshot. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.reverted: - cleanup: True domain_nam...
Defines and starts a new network with specified arguments. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overrid...
def network_running(name, bridge, forward, vport=None, tag=None, autostart=True, connection=None, username=None, password=None): ''' Defines and starts ...
Defines and starts a new pool with specified arguments. .. versionadded:: 2019.2.0 :param ptype: libvirt pool type :param target: full path to the target device or folder. (Default: ``None``) :param permissions: target permissions. See the **Permissions definition** section of the :py:func:`vi...
def pool_running(name, ptype=None, target=None, permissions=None, source=None, transient=False, autostart=True, connection=None, username=None, password=None): '''...
Return ``True`` if service is running name the service's name sig signature to identify with ps CLI Example: .. code-block:: bash salt '*' runit.status <service name>
def status(name, sig=None): ''' Return ``True`` if service is running name the service's name sig signature to identify with ps CLI Example: .. code-block:: bash salt '*' runit.status <service name> ''' if sig: # usual way to do by others (debian_serv...
Return ``True`` if directory <svc_path> is really a service: file <svc_path>/run exists and is executable svc_path the (absolute) directory to check for compatibility
def _is_svc(svc_path): ''' Return ``True`` if directory <svc_path> is really a service: file <svc_path>/run exists and is executable svc_path the (absolute) directory to check for compatibility ''' run_file = os.path.join(svc_path, 'run') if (os.path.exists(svc_path) and os...
Return ``True`` if service <name> is autostarted by sv (file $service_folder/down does not exist) NB: return ``False`` if the service is not enabled. name the service's name CLI Example: .. code-block:: bash salt '*' runit.status_autostart <service name>
def status_autostart(name): ''' Return ``True`` if service <name> is autostarted by sv (file $service_folder/down does not exist) NB: return ``False`` if the service is not enabled. name the service's name CLI Example: .. code-block:: bash salt '*' runit.status_autostart ...
Return list of broken path(s) in SERVICE_DIR that match ``name`` A path is broken if it is a broken symlink or can not be a runit service name a glob for service name. default is '*' CLI Example: .. code-block:: bash salt '*' runit.get_svc_broken_path <service name>
def get_svc_broken_path(name='*'): ''' Return list of broken path(s) in SERVICE_DIR that match ``name`` A path is broken if it is a broken symlink or can not be a runit service name a glob for service name. default is '*' CLI Example: .. code-block:: bash salt '*' runit.get_...
Add a path that may contain available services. Return ``True`` if added (or already present), ``False`` on error. path directory to add to AVAIL_SVR_DIRS
def add_svc_avail_path(path): ''' Add a path that may contain available services. Return ``True`` if added (or already present), ``False`` on error. path directory to add to AVAIL_SVR_DIRS ''' if os.path.exists(path): if path not in AVAIL_SVR_DIRS: AVAIL_SVR_DIRS.app...
Return a list of paths to services with ``name`` that have the specified ``status`` name a glob for service name. default is '*' status None : all services (no filter, default choice) 'DISABLED' : available service(s) that is not enabled 'ENABLED' : enabled service (whet...
def _get_svc_path(name='*', status=None): ''' Return a list of paths to services with ``name`` that have the specified ``status`` name a glob for service name. default is '*' status None : all services (no filter, default choice) 'DISABLED' : available service(s) that is ...
Return list of services that have the specified service ``status`` name a glob for service name. default is '*' status None : all services (no filter, default choice) 'DISABLED' : available service that is not enabled 'ENABLED' : enabled service (whether started on boot ...
def _get_svc_list(name='*', status=None): ''' Return list of services that have the specified service ``status`` name a glob for service name. default is '*' status None : all services (no filter, default choice) 'DISABLED' : available service that is not enabled ...
Returns the list of service's name that are aliased and their alias path(s)
def get_svc_alias(): ''' Returns the list of service's name that are aliased and their alias path(s) ''' ret = {} for d in AVAIL_SVR_DIRS: for el in glob.glob(os.path.join(d, '*')): if not os.path.islink(el): continue psvc = os.readlink(el) ...
Show properties of one or more units/jobs or the manager name the service's name CLI Example: salt '*' service.show <service name>
def show(name): ''' Show properties of one or more units/jobs or the manager name the service's name CLI Example: salt '*' service.show <service name> ''' ret = {} ret['enabled'] = False ret['disabled'] = True ret['running'] = False ret['service_path'] = None ...
Start service ``name`` at boot. Returns ``True`` if operation is successful name the service's name start : False If ``True``, start the service once enabled. CLI Example: .. code-block:: bash salt '*' service.enable <name> [start=True]
def enable(name, start=False, **kwargs): ''' Start service ``name`` at boot. Returns ``True`` if operation is successful name the service's name start : False If ``True``, start the service once enabled. CLI Example: .. code-block:: bash salt '*' service.enable <...
Don't start service ``name`` at boot Returns ``True`` if operation is successful name the service's name stop if True, also stops the service CLI Example: .. code-block:: bash salt '*' service.disable <name> [stop=True]
def disable(name, stop=False, **kwargs): ''' Don't start service ``name`` at boot Returns ``True`` if operation is successful name the service's name stop if True, also stops the service CLI Example: .. code-block:: bash salt '*' service.disable <name> [stop=True...
Remove the service <name> from system. Returns ``True`` if operation is successful. The service will be also stopped. name the service's name CLI Example: .. code-block:: bash salt '*' service.remove <name>
def remove(name): ''' Remove the service <name> from system. Returns ``True`` if operation is successful. The service will be also stopped. name the service's name CLI Example: .. code-block:: bash salt '*' service.remove <name> ''' if not enabled(name): ...
Execute a command and read the output as YAML
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 bucket, key=None, keyid=None, verify_ssl=True, location=None, multiple_env=False, environment='base', prefix='', ...
Connect to S3 and download the metadata for each file in all buckets specified and cache the data to disk.
def _init(creds, bucket, multiple_env, environment, prefix, s3_cache_expire): ''' Connect to S3 and download the metadata for each file in all buckets specified and cache the data to disk. ''' cache_file = _get_buckets_cache_filename(bucket, prefix) exp = time.time() - s3_cache_expire # ch...
Get pillar cache directory. Initialize it if it does not exist.
def _get_cache_dir(): ''' Get pillar cache directory. Initialize it if it does not exist. ''' cache_dir = os.path.join(__opts__['cachedir'], 'pillar_s3fs') if not os.path.isdir(cache_dir): log.debug('Initializing S3 Pillar Cache') os.makedirs(cache_dir) return cache_dir
Return the filename of the cache for bucket contents. Create the path if it does not exist.
def _get_buckets_cache_filename(bucket, prefix): ''' Return the filename of the cache for bucket contents. Create the path if it does not exist. ''' cache_dir = _get_cache_dir() if not os.path.exists(cache_dir): os.makedirs(cache_dir) return os.path.join(cache_dir, '{0}-{1}-files.c...
Retrieve the content of all buckets and cache the metadata to the buckets cache file
def _refresh_buckets_cache_file(creds, cache_file, multiple_env, environment, prefix): ''' Retrieve the content of all buckets and cache the metadata to the buckets cache file ''' # helper s3 query function def __get_s3_meta(): return __utils__['s3.query']( key=creds.key, ...
Return the contents of the buckets cache file
def _read_buckets_cache_file(cache_file): ''' Return the contents of the buckets cache file ''' log.debug('Reading buckets cache file') with salt.utils.files.fopen(cache_file, 'rb') as fp_: data = pickle.load(fp_) return data
Looks for all the files in the S3 bucket cache metadata
def _find_files(metadata): ''' Looks for all the files in the S3 bucket cache metadata ''' ret = {} for bucket, data in six.iteritems(metadata): if bucket not in ret: ret[bucket] = [] # grab the paths from the metadata filePaths = [k['Key'] for k in data] ...
Checks the local cache for the file, if it's old or missing go grab the file from S3 and update the cache
def _get_file_from_s3(creds, metadata, saltenv, bucket, path, cached_file_path): ''' Checks the local cache for the file, if it's old or missing go grab the file from S3 and update the cache ''' # check the local cache... if os.path.isfile(cached_file_path): file_m...
Turn a pass argument into the correct option
def _arg2opt(arg): ''' Turn a pass argument into the correct option ''' res = [o for o, a in option_toggles.items() if a == arg] res += [o for o, a in option_flags.items() if a == arg] return res[0] if res else None
Parse a logadm configuration file.
def _parse_conf(conf_file=default_conf): ''' Parse a logadm configuration file. ''' ret = {} with salt.utils.files.fopen(conf_file, 'r') as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line).strip() if not line: continue ...
Parse a logadm options string
def _parse_options(entry, options, include_unset=True): ''' Parse a logadm options string ''' log_cfg = {} options = shlex.split(options) if not options: return None ## identifier is entry or log? if entry.startswith('/'): log_cfg['log_file'] = entry else: lo...
Show configuration conf_file : string path to logadm.conf, defaults to /etc/logadm.conf name : string optional show only a single entry CLI Example: .. code-block:: bash salt '*' logadm.show_conf salt '*' logadm.show_conf name=/var/log/syslog
def show_conf(conf_file=default_conf, name=None): ''' Show configuration conf_file : string path to logadm.conf, defaults to /etc/logadm.conf name : string optional show only a single entry CLI Example: .. code-block:: bash salt '*' logadm.show_conf salt '*' l...
Show parsed configuration .. versionadded:: 2018.3.0 conf_file : string path to logadm.conf, defaults to /etc/logadm.conf log_file : string optional show only one log file include_unset : boolean include unset flags in output CLI Example: .. code-block:: bash ...
def list_conf(conf_file=default_conf, log_file=None, include_unset=False): ''' Show parsed configuration .. versionadded:: 2018.3.0 conf_file : string path to logadm.conf, defaults to /etc/logadm.conf log_file : string optional show only one log file include_unset : boolean ...
Show which arguments map to which flags and options. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' logadm.show_args
def show_args(): ''' Show which arguments map to which flags and options. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' logadm.show_args ''' mapping = {'flags': {}, 'options': {}} for flag, arg in option_toggles.items(): mapping['flags'][flag] ...
Set up pattern for logging. name : string alias for entryname pattern : string alias for log_file conf_file : string optional path to alternative configuration file kwargs : boolean|string|int optional additional flags and parameters .. note:: ``name`` and `...
def rotate(name, pattern=None, conf_file=default_conf, **kwargs): ''' Set up pattern for logging. name : string alias for entryname pattern : string alias for log_file conf_file : string optional path to alternative configuration file kwargs : boolean|string|int ...
Remove log pattern from logadm CLI Example: .. code-block:: bash salt '*' logadm.remove myapplog
def remove(name, conf_file=default_conf): ''' Remove log pattern from logadm CLI Example: .. code-block:: bash salt '*' logadm.remove myapplog ''' command = "logadm -f {0} -r {1}".format(conf_file, name) result = __salt__['cmd.run_all'](command, python_shell=False) if result['re...
return a list of string encodings to try
def get_encodings(): ''' return a list of string encodings to try ''' encodings = [__salt_system_encoding__] try: sys_enc = sys.getdefaultencoding() except ValueError: # system encoding is nonstandard or malformed sys_enc = None if sys_enc and sys_enc not in encodings: ...
Split a locale specifier. The general format is language[_territory][.codeset][@modifier] [charmap] For example: ca_ES.UTF-8@valencia UTF-8
def split_locale(loc): ''' Split a locale specifier. The general format is language[_territory][.codeset][@modifier] [charmap] For example: ca_ES.UTF-8@valencia UTF-8 ''' def split(st, char): ''' Split a string `st` once by `char`; always return a two-element list ...
Join a locale specifier split in the format returned by split_locale.
def join_locale(comps): ''' Join a locale specifier split in the format returned by split_locale. ''' loc = comps['language'] if comps.get('territory'): loc += '_' + comps['territory'] if comps.get('codeset'): loc += '.' + comps['codeset'] if comps.get('modifier'): lo...
Format a locale specifier according to the format returned by `locale -a`.
def normalize_locale(loc): ''' Format a locale specifier according to the format returned by `locale -a`. ''' comps = split_locale(loc) comps['territory'] = comps['territory'].upper() comps['codeset'] = comps['codeset'].lower().replace('-', '') comps['charmap'] = '' return join_locale(co...
Remove dots from the given data structure
def _remove_dots(src): ''' Remove dots from the given data structure ''' output = {} for key, val in six.iteritems(src): if isinstance(val, dict): val = _remove_dots(val) output[key.replace('.', '-')] = val return output
Return a mongodb connection object
def _get_conn(ret): ''' Return a mongodb connection object ''' _options = _get_options(ret) host = _options.get('host') port = _options.get('port') db_ = _options.get('db') user = _options.get('user') password = _options.get('password') indexes = _options.get('indexes', False) ...
Return the return information associated with a jid
def get_jid(jid): ''' Return the return information associated with a jid ''' conn, mdb = _get_conn(ret=None) ret = {} rdata = mdb.saltReturns.find({'jid': jid}, {'_id': 0}) if rdata: for data in rdata: minion = data['minion'] # return data in the format {<min...
Return the most recent jobs that have executed the named function
def get_fun(fun): ''' Return the most recent jobs that have executed the named function ''' conn, mdb = _get_conn(ret=None) ret = {} rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0}) if rdata: ret = rdata return ret
Return expected path of a Let's Encrypt live cert
def _cert_file(name, cert_type): ''' Return expected path of a Let's Encrypt live cert ''' return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type))
Return the expiry date of a cert :return datetime object of expiry date
def _expires(name): ''' Return the expiry date of a cert :return datetime object of expiry date ''' cert_file = _cert_file(name, 'cert') # Use the salt module if available if 'tls.cert_info' in __salt__: expiry = __salt__['tls.cert_info'](cert_file)['not_after'] # Cobble it toge...
Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date
def _renew_by(name, window=None): ''' Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date ''' expiry = _expires(name) if window is ...
Obtain/renew a certificate from an ACME CA, probably Let's Encrypt. :param name: Common Name of the certificate (DNS name of certificate) :param aliases: subjectAltNames (Additional DNS names on certificate) :param email: e-mail address for interaction with ACME provider :param webroot: True or a full ...
def cert(name, aliases=None, email=None, webroot=None, test_cert=False, renew=None, keysize=None, server=None, owner='root', group='root', mode='0640', certname=None, preferred_challenges=None, tls_sni_0...
Return information about a certificate .. note:: Will output tls.cert_info if that's available, or OpenSSL text if not :param name: CommonName of cert CLI example: .. code-block:: bash salt 'gitlab.example.com' acme.info dev.example.com
def info(name): ''' Return information about a certificate .. note:: Will output tls.cert_info if that's available, or OpenSSL text if not :param name: CommonName of cert CLI example: .. code-block:: bash salt 'gitlab.example.com' acme.info dev.example.com ''' cert_f...
Check if a certificate needs renewal :param name: CommonName of cert :param window: Window in days to renew earlier or True/force to just return True Code example: .. code-block:: python if __salt__['acme.needs_renewal']('dev.example.com'): __salt__['acme.cert']('dev.example.com'...
def needs_renewal(name, window=None): ''' Check if a certificate needs renewal :param name: CommonName of cert :param window: Window in days to renew earlier or True/force to just return True Code example: .. code-block:: python if __salt__['acme.needs_renewal']('dev.example.com'): ...
Split the field in drbd-overview
def _analyse_overview_field(content): ''' Split the field in drbd-overview ''' if "(" in content: # Output like "Connected(2*)" or "UpToDate(2*)" return content.split("(")[0], content.split("(")[0] elif "/" in content: # Output like "Primar/Second" or "UpToDa/UpToDa" ...
Count the number of spaces before the first character
def _count_spaces_startswith(line): ''' Count the number of spaces before the first character ''' if line.split('#')[0].strip() == "": return None spaces = 0 for i in line: if i.isspace(): spaces += 1 else: return spaces
Figure out the sections in drbdadm status
def _analyse_status_type(line): ''' Figure out the sections in drbdadm status ''' spaces = _count_spaces_startswith(line) if spaces is None: return '' switch = { 0: 'RESOURCE', 2: {' disk:': 'LOCALDISK', ' role:': 'PEERNODE', ' connection:': 'PEERNODE'}, 4: {' p...
Analyse the line of local resource of ``drbdadm status``
def _add_res(line): ''' Analyse the line of local resource of ``drbdadm status`` ''' global resource fields = line.strip().split() if resource: ret.append(resource) resource = {} resource["resource name"] = fields[0] resource["local role"] = fields[1].split(":")[1] ...
Analyse the line of volumes of ``drbdadm status``
def _add_volume(line): ''' Analyse the line of volumes of ``drbdadm status`` ''' section = _analyse_status_type(line) fields = line.strip().split() volume = {} for field in fields: volume[field.split(':')[0]] = field.split(':')[1] if section == 'LOCALDISK': resource['lo...
Analyse the line of peer nodes of ``drbdadm status``
def _add_peernode(line): ''' Analyse the line of peer nodes of ``drbdadm status`` ''' global lastpnodevolumes fields = line.strip().split() peernode = {} peernode["peernode name"] = fields[0] #Could be role or connection: peernode[fields[1].split(":")[0]] = fields[1].split(":")[1] ...
Call action for different lines
def _line_parser(line): ''' Call action for different lines ''' section = _analyse_status_type(line) fields = line.strip().split() switch = { '': _empty, 'RESOURCE': _add_res, 'PEERNODE': _add_peernode, 'LOCALDISK': _add_volume, 'PEERDISK': _add_volume, ...
Show status of the DRBD devices, support two nodes only. drbd-overview is removed since drbd-utils-9.6.0, use status instead. CLI Example: .. code-block:: bash salt '*' drbd.overview
def overview(): ''' Show status of the DRBD devices, support two nodes only. drbd-overview is removed since drbd-utils-9.6.0, use status instead. CLI Example: .. code-block:: bash salt '*' drbd.overview ''' cmd = 'drbd-overview' for line in __salt__['cmd.run'](cmd).splitli...
Using drbdadm to show status of the DRBD devices, available in the latest drbd9. Support multiple nodes, multiple volumes. :type name: str :param name: Resource name. :return: drbd status of resource. :rtype: list(dict(res)) CLI Example: .. code-block:: bash salt '*'...
def status(name='all'): ''' Using drbdadm to show status of the DRBD devices, available in the latest drbd9. Support multiple nodes, multiple volumes. :type name: str :param name: Resource name. :return: drbd status of resource. :rtype: list(dict(res)) CLI Example: .....
return from the input string the return code of the powershell command
def _parse_return_code_powershell(string): ''' return from the input string the return code of the powershell command ''' regex = re.search(r'ReturnValue\s*: (\d*)', string) if not regex: return (False, 'Could not parse PowerShell return code.') else: return int(regex.group(1))
Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the command cmd returns the STDOUT of the command
def _psrdp(cmd): ''' Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the command cmd returns the STDOUT of the command ''' rdp = ('$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting ' '-Namespace root\\CIMV2\\TerminalServices -Computer . ' '-Authentic...
List information about the sessions. .. versionadded:: 2016.11.0 :param logged_in_users_only: If True, only return sessions with users logged in. :return: A list containing dictionaries of session information. CLI Example: .. code-block:: bash salt '*' rdp.list_sessions
def list_sessions(logged_in_users_only=False): ''' List information about the sessions. .. versionadded:: 2016.11.0 :param logged_in_users_only: If True, only return sessions with users logged in. :return: A list containing dictionaries of session information. CLI Example: .. code-block:...
Get information about a session. .. versionadded:: 2016.11.0 :param session_id: The numeric Id of the session. :return: A dictionary of session information. CLI Example: .. code-block:: bash salt '*' rdp.get_session session_id salt '*' rdp.get_session 99
def get_session(session_id): ''' Get information about a session. .. versionadded:: 2016.11.0 :param session_id: The numeric Id of the session. :return: A dictionary of session information. CLI Example: .. code-block:: bash salt '*' rdp.get_session session_id salt '*' r...
Disconnect a session. .. versionadded:: 2016.11.0 :param session_id: The numeric Id of the session. :return: A boolean representing whether the disconnect succeeded. CLI Example: .. code-block:: bash salt '*' rdp.disconnect_session session_id salt '*' rdp.disconnect_session 99
def disconnect_session(session_id): ''' Disconnect a session. .. versionadded:: 2016.11.0 :param session_id: The numeric Id of the session. :return: A boolean representing whether the disconnect succeeded. CLI Example: .. code-block:: bash salt '*' rdp.disconnect_session session...
Initiate the logoff of a session. .. versionadded:: 2016.11.0 :param session_id: The numeric Id of the session. :return: A boolean representing whether the logoff succeeded. CLI Example: .. code-block:: bash salt '*' rdp.logoff_session session_id salt '*' rdp.logoff_session 99
def logoff_session(session_id): ''' Initiate the logoff of a session. .. versionadded:: 2016.11.0 :param session_id: The numeric Id of the session. :return: A boolean representing whether the logoff succeeded. CLI Example: .. code-block:: bash salt '*' rdp.logoff_session session...
Return the available fileserver environments. If no backend is provided, then the environments for all configured backends will be returned. backend Narrow fileserver backends to a subset of the enabled ones. .. versionchanged:: 2015.5.0 If all passed backends start with a minus si...
def envs(backend=None, sources=False): ''' Return the available fileserver environments. If no backend is provided, then the environments for all configured backends will be returned. backend Narrow fileserver backends to a subset of the enabled ones. .. versionchanged:: 2015.5.0 ...
.. versionadded:: 2016.11.0 The Salt fileserver caches the files/directories/symlinks for each fileserver backend and environment as they are requested. This is done to help the fileserver scale better. Without this caching, when hundreds/thousands of minions simultaneously ask the master what files ar...
def clear_file_list_cache(saltenv=None, backend=None): ''' .. versionadded:: 2016.11.0 The Salt fileserver caches the files/directories/symlinks for each fileserver backend and environment as they are requested. This is done to help the fileserver scale better. Without this caching, when hundre...
Return a list of files from the salt fileserver saltenv : base The salt fileserver environment to be listed backend Narrow fileserver backends to a subset of the enabled ones. If all passed backends start with a minus sign (``-``), then these backends will be excluded from the ...
def file_list(saltenv='base', backend=None): ''' Return a list of files from the salt fileserver saltenv : base The salt fileserver environment to be listed backend Narrow fileserver backends to a subset of the enabled ones. If all passed backends start with a minus sign (``-``...
Return a list of symlinked files and dirs saltenv : base The salt fileserver environment to be listed backend Narrow fileserver backends to a subset of the enabled ones. If all passed backends start with a minus sign (``-``), then these backends will be excluded from the enable...
def symlink_list(saltenv='base', backend=None): ''' Return a list of symlinked files and dirs saltenv : base The salt fileserver environment to be listed backend Narrow fileserver backends to a subset of the enabled ones. If all passed backends start with a minus sign (``-``), ...