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/disk.py
|
blkid
|
python
|
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
|
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L271-L315
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
tune
|
python
|
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
|
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L318-L354
|
[
"def dump(device, args=None):\n '''\n Return all contents of dumpe2fs for a specified device\n\n CLI Example:\n .. code-block:: bash\n\n salt '*' disk.dump /dev/sda1\n '''\n cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \\\n '--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)\n ret = {}\n opts = [c[2:] for c in cmd.split() if c.startswith('--')]\n out = __salt__['cmd.run_all'](cmd, python_shell=False)\n if out['retcode'] == 0:\n lines = [line for line in out['stdout'].splitlines() if line]\n count = 0\n for line in lines:\n ret[opts[count]] = line\n count = count+1\n if args:\n temp_ret = {}\n for arg in args:\n temp_ret[arg] = ret[arg]\n return temp_ret\n else:\n return ret\n else:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
wipe
|
python
|
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
|
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L357-L377
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
dump
|
python
|
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
|
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L380-L408
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
resize2fs
|
python
|
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
|
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L411-L426
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
format_
|
python
|
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
|
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L431-L502
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
fstype
|
python
|
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
|
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L506-L544
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
_hdparm
|
python
|
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
|
Execute hdparm
Fail hard when required
return output when possible
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L548-L563
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
hdparms
|
python
|
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
|
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L567-L640
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
hpa
|
python
|
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
|
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L644-L696
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
smart_attributes
|
python
|
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
|
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L699-L769
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
iostat
|
python
|
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
|
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L773-L793
|
[
"def _iostat_linux(interval, count, disks):\n if disks is None:\n iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)\n elif isinstance(disks, six.string_types):\n iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)\n else:\n iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))\n\n sys_stats = []\n dev_stats = collections.defaultdict(list)\n sys_header = []\n dev_header = []\n\n ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())\n for line in ret:\n if line.startswith('avg-cpu:'):\n if not sys_header:\n sys_header = tuple(line.split()[1:])\n line = [decimal.Decimal(x) for x in next(ret).split()]\n sys_stats.append(line)\n elif line.startswith('Device:'):\n if not dev_header:\n dev_header = tuple(line.split()[1:])\n while line is not False:\n line = next(ret, False)\n if not line or not line[0].isalnum():\n break\n line = line.split()\n disk = line[0]\n stats = [decimal.Decimal(x) for x in line[1:]]\n dev_stats[disk].append(stats)\n\n iostats = {}\n\n if sys_header:\n iostats['sys'] = _iostats_dict(sys_header, sys_stats)\n\n for disk, stats in dev_stats.items():\n iostats[disk] = _iostats_dict(dev_header, stats)\n\n return iostats\n"
] |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
_iostats_dict
|
python
|
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
|
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L796-L804
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
_iostat_fbsd
|
python
|
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
|
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L807-L860
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
saltstack/salt
|
salt/modules/disk.py
|
_iostat_aix
|
python
|
def _iostat_aix(interval, count, disks):
'''
AIX support to gather and return (averaged) IO stats.
'''
log.debug('DGM disk iostat entry')
if disks is None:
iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count)
else:
iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count)
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
dev_stats = collections.defaultdict(list)
for line in __salt__['cmd.run'](iostat_cmd).splitlines():
# Note: iostat -dD is per-system
#
#root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 9.6 16.4K 4.0 16.4K 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 4.0 4.9 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
#
#hdisk6 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.0 0.0 0.0 0.0
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.3 9.9 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.0 0.0 0.0 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.0 0.0 0.0 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#seen disk name
dsk_comps = line.split(':')
dsk_firsts = dsk_comps[0].split()
disk_name = dsk_firsts[0]
disk_mode = dsk_firsts[1]
fields = dsk_comps[1].split()
if disk_name not in dev_stats.keys():
dev_stats[disk_name] = []
procn = len(dev_stats[disk_name])
dev_stats[disk_name].append({})
dev_stats[disk_name][procn][disk_mode] = {}
dev_stats[disk_name][procn][disk_mode]['fields'] = fields
dev_stats[disk_name][procn][disk_mode]['stats'] = []
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
if disk_mode not in dev_stats[disk_name][0].keys():
dev_stats[disk_name][0][disk_mode] = {}
dev_stats[disk_name][0][disk_mode]['fields'] = fields
dev_stats[disk_name][0][disk_mode]['stats'] = []
else:
line = line.split()
stats = [_parse_numbers(x) for x in line[:]]
dev_stats[disk_name][0][disk_mode]['stats'].append(stats)
iostats = {}
for disk, list_modes in dev_stats.items():
iostats[disk] = {}
for modes in list_modes:
for disk_mode in modes.keys():
fields = modes[disk_mode]['fields']
stats = modes[disk_mode]['stats']
iostats[disk][disk_mode] = _iostats_dict(fields, stats)
return iostats
|
AIX support to gather and return (averaged) IO stats.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L906-L1003
| null |
# -*- coding: utf-8 -*-
'''
Module for managing disks and blockdevices
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import subprocess
import re
import collections
import decimal
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip
# Import salt libs
import salt.utils.decorators
import salt.utils.decorators.path
import salt.utils.path
import salt.utils.platform
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'format_': 'format'
}
log = logging.getLogger(__name__)
HAS_HDPARM = salt.utils.path.which('hdparm') is not None
HAS_IOSTAT = salt.utils.path.which('iostat') is not None
def __virtual__():
'''
Only work on POSIX-like systems
'''
if salt.utils.platform.is_windows():
return False, 'This module doesn\'t work on Windows.'
return True
def _parse_numbers(text):
'''
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K.
Returns a decimal number if the string is a real number,
or the string unchanged otherwise.
'''
if text.isdigit():
return decimal.Decimal(text)
try:
postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'}
if text[-1] in postPrefixes.keys():
v = decimal.Decimal(text[:-1])
v = v * decimal.Decimal(postPrefixes[text[-1]])
return v
else:
return decimal.Decimal(text)
except ValueError:
return text
def _clean_flags(args, caller):
'''
Sanitize flags passed into df
'''
flags = ''
if args is None:
return flags
allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')
for flag in args:
if flag in allowed:
flags += flag
else:
raise CommandExecutionError(
'Invalid flag passed to {0}'.format(caller)
)
return flags
def usage(args=None):
'''
Return usage information for volumes mounted on this minion
.. versionchanged:: 2019.2.0
Default for SunOS changed to 1 kilobyte blocks
CLI Example:
.. code-block:: bash
salt '*' disk.usage
'''
flags = _clean_flags(args, 'disk.usage')
if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux':
log.error('df cannot run without /etc/mtab')
if __grains__.get('virtual_subtype') == 'LXC':
log.error('df command failed and LXC detected. If you are running '
'a Docker container, consider linking /proc/mounts to '
'/etc/mtab or consider running Docker with -privileged')
return {}
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
elif __grains__['kernel'] == 'SunOS':
cmd = 'df -k'
else:
cmd = 'df'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
oldline = None
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
if oldline:
line = oldline + " " + line
comps = line.split()
if len(comps) == 1:
oldline = line
continue
else:
oldline = None
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = {
'filesystem': comps[0],
'512-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
'iused': comps[5],
'ifree': comps[6],
'%iused': comps[7],
}
else:
ret[comps[5]] = {
'filesystem': comps[0],
'1K-blocks': comps[1],
'used': comps[2],
'available': comps[3],
'capacity': comps[4],
}
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
return ret
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
cmd = 'df -iP'
if flags:
cmd += ' -{0}'.format(flags)
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if line.startswith('Filesystem'):
continue
comps = line.split()
# Don't choke on empty lines
if not comps:
continue
try:
if __grains__['kernel'] == 'OpenBSD':
ret[comps[8]] = {
'inodes': int(comps[5]) + int(comps[6]),
'used': comps[5],
'free': comps[6],
'use': comps[7],
'filesystem': comps[0],
}
elif __grains__['kernel'] == 'AIX':
ret[comps[6]] = {
'inodes': comps[4],
'used': comps[5],
'free': comps[2],
'use': comps[5],
'filesystem': comps[0],
}
else:
ret[comps[5]] = {
'inodes': comps[1],
'used': comps[2],
'free': comps[3],
'use': comps[4],
'filesystem': comps[0],
}
except (IndexError, ValueError):
log.error('Problem parsing inode usage information')
ret = {}
return ret
def percent(args=None):
'''
Return partition information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.percent /var
'''
if __grains__['kernel'] == 'Linux':
cmd = 'df -P'
elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX':
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if not line:
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while len(comps) >= 2 and not comps[1].isdigit():
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
if len(comps) < 2:
continue
try:
if __grains__['kernel'] == 'Darwin':
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if args and args not in ret:
log.error(
'Problem parsing disk usage information: Partition \'%s\' '
'does not exist!', args
)
ret = {}
elif args:
return ret[args]
return ret
@salt.utils.decorators.path.which('blkid')
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid /dev/sda
salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d'
salt '*' disk.blkid token='TYPE=ext4'
'''
cmd = ['blkid']
if device:
cmd.append(device)
elif token:
cmd.extend(['-t', token])
ret = {}
blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False)
if blkid_result['retcode'] > 0:
return ret
for line in blkid_result['stdout'].splitlines():
if not line:
continue
comps = line.split()
device = comps[0][:-1]
info = {}
device_attributes = re.split(('\"*\"'), line.partition(' ')[2])
for key, value in zip(*[iter(device_attributes)]*2):
key = key.strip('=').strip(' ')
info[key] = value.strip('"')
ret[device] = info
return ret
def tune(device, **kwargs):
'''
Set attributes for the specified device
CLI Example:
.. code-block:: bash
salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True
Valid options are: ``read-ahead``, ``filesystem-read-ahead``,
``read-only``, ``read-write``.
See the ``blockdev(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'read-ahead': 'setra',
'filesystem-read-ahead': 'setfra',
'read-only': 'setro',
'read-write': 'setrw'}
opts = ''
args = []
for key in kwargs:
if key in kwarg_map:
switch = kwarg_map[key]
if key != 'read-write':
args.append(switch.replace('set', 'get'))
else:
args.append('getro')
if kwargs[key] == 'True' or kwargs[key] is True:
opts += '--{0} '.format(key)
else:
opts += '--{0} {1} '.format(switch, kwargs[key])
cmd = 'blockdev {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return dump(device, args)
def wipe(device):
'''
Remove the filesystem information
CLI Example:
.. code-block:: bash
salt '*' disk.wipe /dev/sda1
'''
cmd = 'wipefs -a {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
else:
log.error('Error wiping device %s: %s', device, out['stderr'])
return False
def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' disk.dump /dev/sda1
'''
cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \
'--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device)
ret = {}
opts = [c[2:] for c in cmd.split() if c.startswith('--')]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] == 0:
lines = [line for line in out['stdout'].splitlines() if line]
count = 0
for line in lines:
ret[opts[count]] = line
count = count+1
if args:
temp_ret = {}
for arg in args:
temp_ret[arg] = ret[arg]
return temp_ret
else:
return ret
else:
return False
def resize2fs(device):
'''
Resizes the filesystem.
CLI Example:
.. code-block:: bash
salt '*' disk.resize2fs /dev/sda1
'''
cmd = 'resize2fs {0}'.format(device)
try:
out = __salt__['cmd.run_all'](cmd, python_shell=False)
except subprocess.CalledProcessError as err:
return False
if out['retcode'] == 0:
return True
@salt.utils.decorators.path.which('sync')
@salt.utils.decorators.path.which('mkfs')
def format_(device,
fs_type='ext4',
inode_size=None,
lazy_itable_init=None,
fat=None,
force=False):
'''
Format a filesystem onto a device
.. versionadded:: 2016.11.0
device
The device in which to create the new filesystem
fs_type
The type of filesystem to create
inode_size
Size of the inodes
This option is only enabled for ext and xfs filesystems
lazy_itable_init
If enabled and the uninit_bg feature is enabled, the inode table will
not be fully initialized by mke2fs. This speeds up filesystem
initialization noticeably, but it requires the kernel to finish
initializing the filesystem in the background when the filesystem
is first mounted. If the option value is omitted, it defaults to 1 to
enable lazy inode table zeroing.
This option is only enabled for ext filesystems
fat
FAT size option. Can be 12, 16 or 32, and can only be used on
fat or vfat filesystems.
force
Force mke2fs to create a filesystem, even if the specified device is
not a partition on a block special device. This option is only enabled
for ext and xfs filesystems
This option is dangerous, use it with caution.
CLI Example:
.. code-block:: bash
salt '*' disk.format /dev/sdX1
'''
cmd = ['mkfs', '-t', six.text_type(fs_type)]
if inode_size is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-i', six.text_type(inode_size)])
elif fs_type == 'xfs':
cmd.extend(['-i', 'size={0}'.format(inode_size)])
if lazy_itable_init is not None:
if fs_type[:3] == 'ext':
cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)])
if fat is not None and fat in (12, 16, 32):
if fs_type[-3:] == 'fat':
cmd.extend(['-F', fat])
if force:
if fs_type[:3] == 'ext':
cmd.append('-F')
elif fs_type == 'xfs':
cmd.append('-f')
cmd.append(six.text_type(device))
mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0
sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0
return all([mkfs_success, sync_success])
@salt.utils.decorators.path.which_bin(['lsblk', 'df'])
def fstype(device):
'''
Return the filesystem name of the specified device
.. versionadded:: 2016.11.0
device
The name of the device
CLI Example:
.. code-block:: bash
salt '*' disk.fstype /dev/sdX1
'''
if salt.utils.path.which('lsblk'):
lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines()
if len(lsblk_out) > 1:
fs_type = lsblk_out[1].strip()
if fs_type:
return fs_type
if salt.utils.path.which('df'):
# the fstype was not set on the block device, so inspect the filesystem
# itself for its type
if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'):
df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split()
if len(df_out) > 2:
fs_type = df_out[2]
if fs_type:
return fs_type
else:
df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines()
if len(df_out) > 1:
fs_type = df_out[1]
if fs_type:
return fs_type
return ''
@salt.utils.decorators.depends(HAS_HDPARM)
def _hdparm(args, failhard=True):
'''
Execute hdparm
Fail hard when required
return output when possible
'''
cmd = 'hdparm {0}'.format(args)
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
msg = '{0}: {1}'.format(cmd, result['stderr'])
if failhard:
raise CommandExecutionError(msg)
else:
log.warning(msg)
return result['stdout']
@salt.utils.decorators.depends(HAS_HDPARM)
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkMmNnQrRuW'
if args is None:
args = all_parms
elif isinstance(args, (list, tuple)):
args = ''.join(args)
if not isinstance(disks, (list, tuple)):
disks = [disks]
out = {}
for disk in disks:
if not disk.startswith('/dev'):
disk = '/dev/{0}'.format(disk)
disk_data = {}
for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines():
line = line.strip()
if not line or line == disk + ':':
continue
if ':' in line:
key, vals = line.split(':', 1)
key = re.sub(r' is$', '', key)
elif '=' in line:
key, vals = line.split('=', 1)
else:
continue
key = key.strip().lower().replace(' ', '_')
vals = vals.strip()
rvals = []
if re.match(r'[0-9]+ \(.*\)', vals):
vals = vals.split(' ')
rvals.append(int(vals[0]))
rvals.append(vals[1].strip('()'))
else:
valdict = {}
for val in re.split(r'[/,]', vals.strip()):
val = val.strip()
try:
val = int(val)
rvals.append(val)
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
val = val.strip()
if val:
valdict[deep_key] = val
elif val:
rvals.append(val)
if valdict:
rvals.append(valdict)
if not rvals:
continue
elif len(rvals) == 1:
rvals = rvals[0]
disk_data[key] = rvals
out[disk] = disk_data
return out
@salt.utils.decorators.depends(HAS_HDPARM)
def hpa(disks, size=None):
'''
Get/set Host Protected Area settings
T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record)
and PARTIES (Protected Area Run Time Interface Extension Services), allowing
for a Host Protected Area on a disk.
It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's
.. warning::
Setting the HPA might clobber your data, be very careful with this on active disks!
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hpa /dev/sda
salt '*' disk.hpa /dev/sda 5%
salt '*' disk.hpa /dev/sda 10543256
'''
hpa_data = {}
for disk, data in hdparms(disks, 'N').items():
visible, total, status = data.values()[0]
if visible == total or 'disabled' in status:
hpa_data[disk] = {
'total': total
}
else:
hpa_data[disk] = {
'total': total,
'visible': visible,
'hidden': total - visible
}
if size is None:
return hpa_data
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
size /= 100
if size <= 0:
size = data['total']
_hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
def smart_attributes(dev, attributes=None, values=None):
'''
Fetch SMART attributes
Providing attributes will deliver only requested attributes
Providing values will deliver only requested values for attributes
Default is the Backblaze recommended
set (https://www.backblaze.com/blog/hard-drive-smart-stats/):
(5,187,188,197,198)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.smart_attributes /dev/sda
salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198)
'''
if not dev.startswith('/dev/'):
dev = '/dev/' + dev
cmd = 'smartctl --attributes {0}'.format(dev)
smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')
if smart_result['retcode'] != 0:
raise CommandExecutionError(smart_result['stderr'])
smart_result = iter(smart_result['stdout'].splitlines())
fields = []
for line in smart_result:
if line.startswith('ID#'):
fields = re.split(r'\s+', line.strip())
fields = [key.lower() for key in fields[1:]]
break
if values is not None:
fields = [field if field in values else '_' for field in fields]
smart_attr = {}
for line in smart_result:
if not re.match(r'[\s]*\d', line):
break
line = re.split(r'\s+', line.strip(), maxsplit=len(fields))
attr = int(line[0])
if attributes is not None and attr not in attributes:
continue
data = dict(zip(fields, line[1:]))
try:
del data['_']
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except Exception:
pass
data[field] = val
smart_attr[attr] = data
return smart_attr
@salt.utils.decorators.depends(HAS_IOSTAT)
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_linux():
return _iostat_linux(interval, count, disks)
elif salt.utils.platform.is_freebsd():
return _iostat_fbsd(interval, count, disks)
elif salt.utils.platform.is_aix():
return _iostat_aix(interval, count, disks)
def _iostats_dict(header, stats):
'''
Transpose collected data, average it, stomp it in dict using header
Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq
'''
stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
stats = dict(zip(header, stats))
return stats
def _iostat_fbsd(interval, count, disks):
'''
Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax
'''
if disks is None:
iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
h_len = 1000 # randomly absurdly high
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if not line.startswith('device'):
continue
elif not dev_header:
dev_header = line.split()[1:]
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
# h_len will become smallest number of fields in stat lines
if len(stats) < h_len:
h_len = len(stats)
dev_stats[disk].append(stats)
iostats = {}
# The header was longer than the smallest number of fields
# Therefore the sys stats are hidden in there
if h_len < len(dev_header):
sys_header = dev_header[h_len:]
dev_header = dev_header[0:h_len]
for disk, stats in dev_stats.items():
if len(stats[0]) > h_len:
sys_stats = [stat[h_len:] for stat in stats]
dev_stats[disk] = [stat[0:h_len] for stat in stats]
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
def _iostat_linux(interval, count, disks):
if disks is None:
iostat_cmd = 'iostat -x {0} {1} '.format(interval, count)
elif isinstance(disks, six.string_types):
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks)
else:
iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks))
sys_stats = []
dev_stats = collections.defaultdict(list)
sys_header = []
dev_header = []
ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines())
for line in ret:
if line.startswith('avg-cpu:'):
if not sys_header:
sys_header = tuple(line.split()[1:])
line = [decimal.Decimal(x) for x in next(ret).split()]
sys_stats.append(line)
elif line.startswith('Device:'):
if not dev_header:
dev_header = tuple(line.split()[1:])
while line is not False:
line = next(ret, False)
if not line or not line[0].isalnum():
break
line = line.split()
disk = line[0]
stats = [decimal.Decimal(x) for x in line[1:]]
dev_stats[disk].append(stats)
iostats = {}
if sys_header:
iostats['sys'] = _iostats_dict(sys_header, sys_stats)
for disk, stats in dev_stats.items():
iostats[disk] = _iostats_dict(dev_header, stats)
return iostats
|
saltstack/salt
|
salt/beacons/http_status.py
|
validate
|
python
|
def validate(config):
'''
Validate the beacon configuration
'''
valid = True
messages = []
if not isinstance(config, list):
valid = False
messages.append('[-] Configuration for %s beacon must be a list', config)
else:
_config = {}
list(map(_config.update, config))
try:
sites = _config.get('sites', {})
except AttributeError:
valid = False
messages.append('[-] Sites for %s beacon must be a dict', __virtualname__)
if not sites:
valid = False
messages.append('[-] Configuration does not contain sites')
for site, settings in sites.items():
if required_site_attributes.isdisjoint(set(settings.keys())):
valid = False
messages.append('[-] Sites for {} beacon requires {}'.format(__virtualname__,
required_site_attributes))
log.debug('[+] site: %s', site)
log.debug('[+] settings: %s', settings)
for optional_attrs in itertools.chain(settings.get(attr, []) for attr in optional_site_attributes):
for item in optional_attrs:
cmp = item.get('comp')
if cmp and cmp not in comparisons:
valid = False
messages.append('[-] Invalid comparison operator %s', cmp)
messages.append('[+] Valid beacon configuration')
return valid, messages
|
Validate the beacon configuration
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/http_status.py#L45-L85
| null |
# -*- coding: utf-8 -*-
'''
Beacon to manage and report the status of a server status endpoint.
Fire an event when specified values don't match returned response.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import operator
import re
import requests
import itertools
import salt.utils.data
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__virtualname__ = 'http_status'
comparisons = {
'==': operator.eq,
'<': operator.lt,
'>': operator.gt,
'<=': operator.le,
'>=': operator.ge,
'!=': operator.ne,
'search': re.search
}
attr_func_map = {
'status': lambda x: x.status_code,
'content': lambda x: x.json()
}
required_site_attributes = {'url'}
optional_site_attributes = {'content', 'status'}
def __virtual__():
return __virtualname__
def beacon(config):
'''
Check on different service status reported by the django-server-status
library.
.. code-block:: yaml
beacons:
http_status:
- sites:
example-site-1:
url: "https://example.com/status"
timeout: 30
content-type: json
status:
- value: 400
comp: <
- value: 300
comp: '>='
content:
- path: 'certificate:status'
value: down
comp: '=='
- path: 'status_all'
value: down
comp: '=='
- interval: 10
'''
ret = []
_config = {}
list(map(_config.update, config))
for site, site_config in _config.get('sites', {}).items():
url = site_config.pop('url')
content_type = site_config.pop('content_type', 'json')
try:
r = requests.get(url, timeout=site_config.pop('timeout', 30))
except requests.exceptions.RequestException as e:
log.info("Request failed: %s", e)
if r.raise_for_status:
log.info('[-] Response from status endpoint was invalid: '
'%s', r.status_code)
_failed = {'status_code': r.status_code,
'url': url}
ret.append(_failed)
continue
for attr, checks in site_config.items():
for check in checks:
log.debug('[+] response_item: %s', attr)
attr_path = check.get('path', '')
comp = comparisons[check['comp']]
expected_value = check['value']
if attr_path:
received_value = salt.utils.data.traverse_dict_and_list(attr_func_map[attr](r), attr_path)
else:
received_value = attr_func_map[attr](r)
if received_value is None:
log.info('[-] No data found at location %s for url %s', attr_path, url)
continue
log.debug('[+] expected_value: %s', expected_value)
log.debug('[+] received_value: %s', received_value)
if not comp(expected_value, received_value):
_failed = {'expected': expected_value,
'received': received_value,
'url': url,
'path': attr_path
}
ret.append(_failed)
return ret
|
saltstack/salt
|
salt/beacons/http_status.py
|
beacon
|
python
|
def beacon(config):
'''
Check on different service status reported by the django-server-status
library.
.. code-block:: yaml
beacons:
http_status:
- sites:
example-site-1:
url: "https://example.com/status"
timeout: 30
content-type: json
status:
- value: 400
comp: <
- value: 300
comp: '>='
content:
- path: 'certificate:status'
value: down
comp: '=='
- path: 'status_all'
value: down
comp: '=='
- interval: 10
'''
ret = []
_config = {}
list(map(_config.update, config))
for site, site_config in _config.get('sites', {}).items():
url = site_config.pop('url')
content_type = site_config.pop('content_type', 'json')
try:
r = requests.get(url, timeout=site_config.pop('timeout', 30))
except requests.exceptions.RequestException as e:
log.info("Request failed: %s", e)
if r.raise_for_status:
log.info('[-] Response from status endpoint was invalid: '
'%s', r.status_code)
_failed = {'status_code': r.status_code,
'url': url}
ret.append(_failed)
continue
for attr, checks in site_config.items():
for check in checks:
log.debug('[+] response_item: %s', attr)
attr_path = check.get('path', '')
comp = comparisons[check['comp']]
expected_value = check['value']
if attr_path:
received_value = salt.utils.data.traverse_dict_and_list(attr_func_map[attr](r), attr_path)
else:
received_value = attr_func_map[attr](r)
if received_value is None:
log.info('[-] No data found at location %s for url %s', attr_path, url)
continue
log.debug('[+] expected_value: %s', expected_value)
log.debug('[+] received_value: %s', received_value)
if not comp(expected_value, received_value):
_failed = {'expected': expected_value,
'received': received_value,
'url': url,
'path': attr_path
}
ret.append(_failed)
return ret
|
Check on different service status reported by the django-server-status
library.
.. code-block:: yaml
beacons:
http_status:
- sites:
example-site-1:
url: "https://example.com/status"
timeout: 30
content-type: json
status:
- value: 400
comp: <
- value: 300
comp: '>='
content:
- path: 'certificate:status'
value: down
comp: '=='
- path: 'status_all'
value: down
comp: '=='
- interval: 10
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/http_status.py#L88-L158
| null |
# -*- coding: utf-8 -*-
'''
Beacon to manage and report the status of a server status endpoint.
Fire an event when specified values don't match returned response.
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import operator
import re
import requests
import itertools
import salt.utils.data
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__virtualname__ = 'http_status'
comparisons = {
'==': operator.eq,
'<': operator.lt,
'>': operator.gt,
'<=': operator.le,
'>=': operator.ge,
'!=': operator.ne,
'search': re.search
}
attr_func_map = {
'status': lambda x: x.status_code,
'content': lambda x: x.json()
}
required_site_attributes = {'url'}
optional_site_attributes = {'content', 'status'}
def __virtual__():
return __virtualname__
def validate(config):
'''
Validate the beacon configuration
'''
valid = True
messages = []
if not isinstance(config, list):
valid = False
messages.append('[-] Configuration for %s beacon must be a list', config)
else:
_config = {}
list(map(_config.update, config))
try:
sites = _config.get('sites', {})
except AttributeError:
valid = False
messages.append('[-] Sites for %s beacon must be a dict', __virtualname__)
if not sites:
valid = False
messages.append('[-] Configuration does not contain sites')
for site, settings in sites.items():
if required_site_attributes.isdisjoint(set(settings.keys())):
valid = False
messages.append('[-] Sites for {} beacon requires {}'.format(__virtualname__,
required_site_attributes))
log.debug('[+] site: %s', site)
log.debug('[+] settings: %s', settings)
for optional_attrs in itertools.chain(settings.get(attr, []) for attr in optional_site_attributes):
for item in optional_attrs:
cmp = item.get('comp')
if cmp and cmp not in comparisons:
valid = False
messages.append('[-] Invalid comparison operator %s', cmp)
messages.append('[+] Valid beacon configuration')
return valid, messages
|
saltstack/salt
|
salt/modules/http.py
|
query
|
python
|
def query(url, **kwargs):
'''
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.query http://somelink.com/
salt '*' http.query http://somelink.com/ method=POST \
params='key1=val1&key2=val2'
salt '*' http.query http://somelink.com/ method=POST \
data='<xml>somecontent</xml>'
For more information about the ``http.query`` module, refer to the
:ref:`HTTP Tutorial <tutorial-http>`.
'''
opts = __opts__.copy()
if 'opts' in kwargs:
opts.update(kwargs['opts'])
del kwargs['opts']
return salt.utils.http.query(url=url, opts=opts, **kwargs)
|
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.query http://somelink.com/
salt '*' http.query http://somelink.com/ method=POST \
params='key1=val1&key2=val2'
salt '*' http.query http://somelink.com/ method=POST \
data='<xml>somecontent</xml>'
For more information about the ``http.query`` module, refer to the
:ref:`HTTP Tutorial <tutorial-http>`.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/http.py#L17-L44
| null |
# -*- coding: utf-8 -*-
'''
Module for making various web calls. Primarily designed for webhooks and the
like, but also useful for basic http testing.
.. versionadded:: 2015.5.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.http
def wait_for_successful_query(url, wait_for=300, **kwargs):
'''
Query a resource until a successful response, and decode the return data
CLI Example:
.. code-block:: bash
salt '*' http.wait_for_successful_query http://somelink.com/ wait_for=160
'''
starttime = time.time()
while True:
caught_exception = None
result = None
try:
result = query(url=url, **kwargs)
if not result.get('Error') and not result.get('error'):
return result
except Exception as exc:
caught_exception = exc
if time.time() > starttime + wait_for:
if not result and caught_exception:
# workaround pylint bug https://www.logilab.org/ticket/3207
raise caught_exception # pylint: disable=E0702
return result
def update_ca_bundle(target=None, source=None, merge_files=None):
'''
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle
salt '*' http.update_ca_bundle target=/path/to/cacerts.pem
salt '*' http.update_ca_bundle source=https://example.com/cacerts.pem
If the ``target`` is not specified, it will be pulled from the ``ca_cert``
configuration variable available to the minion. If it cannot be found there,
it will be placed at ``<<FILE_ROOTS>>/cacerts.pem``.
If the ``source`` is not specified, it will be pulled from the
``ca_cert_url`` configuration variable available to the minion. If it cannot
be found, it will be downloaded from the cURL website, using an http (not
https) URL. USING THE DEFAULT URL SHOULD BE AVOIDED!
``merge_files`` may also be specified, which includes a string or list of
strings representing a file or files to be appended to the end of the CA
bundle, once it is downloaded.
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle merge_files=/path/to/mycert.pem
'''
if target is None:
target = __salt__['config.get']('ca_bundle', None)
if source is None:
source = __salt__['config.get']('ca_bundle_url', None)
return salt.utils.http.update_ca_bundle(
target, source, __opts__, merge_files
)
|
saltstack/salt
|
salt/modules/http.py
|
wait_for_successful_query
|
python
|
def wait_for_successful_query(url, wait_for=300, **kwargs):
'''
Query a resource until a successful response, and decode the return data
CLI Example:
.. code-block:: bash
salt '*' http.wait_for_successful_query http://somelink.com/ wait_for=160
'''
starttime = time.time()
while True:
caught_exception = None
result = None
try:
result = query(url=url, **kwargs)
if not result.get('Error') and not result.get('error'):
return result
except Exception as exc:
caught_exception = exc
if time.time() > starttime + wait_for:
if not result and caught_exception:
# workaround pylint bug https://www.logilab.org/ticket/3207
raise caught_exception # pylint: disable=E0702
return result
|
Query a resource until a successful response, and decode the return data
CLI Example:
.. code-block:: bash
salt '*' http.wait_for_successful_query http://somelink.com/ wait_for=160
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/http.py#L47-L75
|
[
"def query(url, **kwargs):\n '''\n Query a resource, and decode the return data\n\n Passes through all the parameters described in the\n :py:func:`utils.http.query function <salt.utils.http.query>`:\n\n .. autofunction:: salt.utils.http.query\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' http.query http://somelink.com/\n salt '*' http.query http://somelink.com/ method=POST \\\n params='key1=val1&key2=val2'\n salt '*' http.query http://somelink.com/ method=POST \\\n data='<xml>somecontent</xml>'\n\n For more information about the ``http.query`` module, refer to the\n :ref:`HTTP Tutorial <tutorial-http>`.\n '''\n opts = __opts__.copy()\n if 'opts' in kwargs:\n opts.update(kwargs['opts'])\n del kwargs['opts']\n\n return salt.utils.http.query(url=url, opts=opts, **kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for making various web calls. Primarily designed for webhooks and the
like, but also useful for basic http testing.
.. versionadded:: 2015.5.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.http
def query(url, **kwargs):
'''
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.query http://somelink.com/
salt '*' http.query http://somelink.com/ method=POST \
params='key1=val1&key2=val2'
salt '*' http.query http://somelink.com/ method=POST \
data='<xml>somecontent</xml>'
For more information about the ``http.query`` module, refer to the
:ref:`HTTP Tutorial <tutorial-http>`.
'''
opts = __opts__.copy()
if 'opts' in kwargs:
opts.update(kwargs['opts'])
del kwargs['opts']
return salt.utils.http.query(url=url, opts=opts, **kwargs)
def update_ca_bundle(target=None, source=None, merge_files=None):
'''
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle
salt '*' http.update_ca_bundle target=/path/to/cacerts.pem
salt '*' http.update_ca_bundle source=https://example.com/cacerts.pem
If the ``target`` is not specified, it will be pulled from the ``ca_cert``
configuration variable available to the minion. If it cannot be found there,
it will be placed at ``<<FILE_ROOTS>>/cacerts.pem``.
If the ``source`` is not specified, it will be pulled from the
``ca_cert_url`` configuration variable available to the minion. If it cannot
be found, it will be downloaded from the cURL website, using an http (not
https) URL. USING THE DEFAULT URL SHOULD BE AVOIDED!
``merge_files`` may also be specified, which includes a string or list of
strings representing a file or files to be appended to the end of the CA
bundle, once it is downloaded.
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle merge_files=/path/to/mycert.pem
'''
if target is None:
target = __salt__['config.get']('ca_bundle', None)
if source is None:
source = __salt__['config.get']('ca_bundle_url', None)
return salt.utils.http.update_ca_bundle(
target, source, __opts__, merge_files
)
|
saltstack/salt
|
salt/modules/http.py
|
update_ca_bundle
|
python
|
def update_ca_bundle(target=None, source=None, merge_files=None):
'''
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle
salt '*' http.update_ca_bundle target=/path/to/cacerts.pem
salt '*' http.update_ca_bundle source=https://example.com/cacerts.pem
If the ``target`` is not specified, it will be pulled from the ``ca_cert``
configuration variable available to the minion. If it cannot be found there,
it will be placed at ``<<FILE_ROOTS>>/cacerts.pem``.
If the ``source`` is not specified, it will be pulled from the
``ca_cert_url`` configuration variable available to the minion. If it cannot
be found, it will be downloaded from the cURL website, using an http (not
https) URL. USING THE DEFAULT URL SHOULD BE AVOIDED!
``merge_files`` may also be specified, which includes a string or list of
strings representing a file or files to be appended to the end of the CA
bundle, once it is downloaded.
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle merge_files=/path/to/mycert.pem
'''
if target is None:
target = __salt__['config.get']('ca_bundle', None)
if source is None:
source = __salt__['config.get']('ca_bundle_url', None)
return salt.utils.http.update_ca_bundle(
target, source, __opts__, merge_files
)
|
Update the local CA bundle file from a URL
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle
salt '*' http.update_ca_bundle target=/path/to/cacerts.pem
salt '*' http.update_ca_bundle source=https://example.com/cacerts.pem
If the ``target`` is not specified, it will be pulled from the ``ca_cert``
configuration variable available to the minion. If it cannot be found there,
it will be placed at ``<<FILE_ROOTS>>/cacerts.pem``.
If the ``source`` is not specified, it will be pulled from the
``ca_cert_url`` configuration variable available to the minion. If it cannot
be found, it will be downloaded from the cURL website, using an http (not
https) URL. USING THE DEFAULT URL SHOULD BE AVOIDED!
``merge_files`` may also be specified, which includes a string or list of
strings representing a file or files to be appended to the end of the CA
bundle, once it is downloaded.
CLI Example:
.. code-block:: bash
salt '*' http.update_ca_bundle merge_files=/path/to/mycert.pem
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/http.py#L78-L119
|
[
"def update_ca_bundle(\n target=None,\n source=None,\n opts=None,\n merge_files=None,\n ):\n '''\n Attempt to update the CA bundle file from a URL\n\n If not specified, the local location on disk (``target``) will be\n auto-detected, if possible. If it is not found, then a new location on disk\n will be created and updated.\n\n The default ``source`` is:\n\n http://curl.haxx.se/ca/cacert.pem\n\n This is based on the information at:\n\n http://curl.haxx.se/docs/caextract.html\n\n A string or list of strings representing files to be appended to the end of\n the CA bundle file may also be passed through as ``merge_files``.\n '''\n if opts is None:\n opts = {}\n\n if target is None:\n target = get_ca_bundle(opts)\n\n if target is None:\n log.error('Unable to detect location to write CA bundle to')\n return\n\n if source is None:\n source = opts.get('ca_bundle_url', 'http://curl.haxx.se/ca/cacert.pem')\n\n log.debug('Attempting to download %s to %s', source, target)\n query(\n source,\n text=True,\n decode=False,\n headers=False,\n status=False,\n text_out=target\n )\n\n if merge_files is not None:\n if isinstance(merge_files, six.string_types):\n merge_files = [merge_files]\n\n if not isinstance(merge_files, list):\n log.error('A value was passed as merge_files which was not either '\n 'a string or a list')\n return\n\n merge_content = ''\n\n for cert_file in merge_files:\n if os.path.exists(cert_file):\n log.debug(\n 'Queueing up %s to be appended to %s',\n cert_file, target\n )\n try:\n with salt.utils.files.fopen(cert_file, 'r') as fcf:\n merge_content = '\\n'.join((merge_content, fcf.read()))\n except IOError as exc:\n log.error(\n 'Reading from %s caused the following error: %s',\n cert_file, exc\n )\n\n if merge_content:\n log.debug('Appending merge_files to %s', target)\n try:\n with salt.utils.files.fopen(target, 'a') as tfp:\n tfp.write('\\n')\n tfp.write(merge_content)\n except IOError as exc:\n log.error(\n 'Writing to %s caused the following error: %s',\n target, exc\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Module for making various web calls. Primarily designed for webhooks and the
like, but also useful for basic http testing.
.. versionadded:: 2015.5.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
# Import Salt libs
import salt.utils.http
def query(url, **kwargs):
'''
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.query http://somelink.com/
salt '*' http.query http://somelink.com/ method=POST \
params='key1=val1&key2=val2'
salt '*' http.query http://somelink.com/ method=POST \
data='<xml>somecontent</xml>'
For more information about the ``http.query`` module, refer to the
:ref:`HTTP Tutorial <tutorial-http>`.
'''
opts = __opts__.copy()
if 'opts' in kwargs:
opts.update(kwargs['opts'])
del kwargs['opts']
return salt.utils.http.query(url=url, opts=opts, **kwargs)
def wait_for_successful_query(url, wait_for=300, **kwargs):
'''
Query a resource until a successful response, and decode the return data
CLI Example:
.. code-block:: bash
salt '*' http.wait_for_successful_query http://somelink.com/ wait_for=160
'''
starttime = time.time()
while True:
caught_exception = None
result = None
try:
result = query(url=url, **kwargs)
if not result.get('Error') and not result.get('error'):
return result
except Exception as exc:
caught_exception = exc
if time.time() > starttime + wait_for:
if not result and caught_exception:
# workaround pylint bug https://www.logilab.org/ticket/3207
raise caught_exception # pylint: disable=E0702
return result
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
exists
|
python
|
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
|
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L91-L108
|
[
"def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,\n region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613\n '''\n Get a group object given a name, name and vpc_id/vpc_name or group_id. Return\n a boto.ec2.securitygroup.SecurityGroup object if the group is found, else\n return None.\n '''\n if vpc_name and vpc_id:\n raise SaltInvocationError('The params \\'vpc_id\\' and \\'vpc_name\\' '\n 'are mutually exclusive.')\n if vpc_name:\n try:\n vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile)\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if name:\n if vpc_id is None:\n log.debug('getting group for %s', name)\n group_filter = {'group-name': name}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n # security groups can have the same name if groups exist in both\n # EC2-Classic and EC2-VPC\n # iterate through groups to ensure we return the EC2-Classic\n # security group\n for group in filtered_groups:\n # a group in EC2-Classic will have vpc_id set to None\n if group.vpc_id is None:\n return group\n # If there are more security groups, and no vpc_id, we can't know which one to choose.\n if len(filtered_groups) > 1:\n raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')\n elif len(filtered_groups) == 1:\n return filtered_groups[0]\n return None\n elif vpc_id:\n log.debug('getting group for %s in vpc_id %s', name, vpc_id)\n group_filter = {'group-name': name, 'vpc_id': vpc_id}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n if len(filtered_groups) == 1:\n return filtered_groups[0]\n else:\n return None\n else:\n return None\n elif group_id:\n try:\n groups = conn.get_all_security_groups(group_ids=[group_id])\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if len(groups) == 1:\n return groups[0]\n else:\n return None\n else:\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
_split_rules
|
python
|
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
|
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L118-L140
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
_get_group
|
python
|
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
|
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L143-L200
|
[
"def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,\n profile=None):\n data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile)\n return data.get('id')\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
get_all_security_groups
|
python
|
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
|
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L239-L298
|
[
"def _parse_rules(sg, rules):\n _rules = []\n for rule in rules:\n log.debug('examining rule %s for group %s', rule, sg.id)\n attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']\n _rule = odict.OrderedDict()\n for attr in attrs:\n val = getattr(rule, attr)\n if not val:\n continue\n if attr == 'grants':\n _grants = []\n for grant in val:\n log.debug('examining grant %s for', grant)\n g_attrs = {'name': 'source_group_name',\n 'owner_id': 'source_group_owner_id',\n 'group_id': 'source_group_group_id',\n 'cidr_ip': 'cidr_ip'}\n _grant = odict.OrderedDict()\n for g_attr, g_attr_map in six.iteritems(g_attrs):\n g_val = getattr(grant, g_attr)\n if not g_val:\n continue\n _grant[g_attr_map] = g_val\n _grants.append(_grant)\n _rule['grants'] = _grants\n elif attr == 'from_port':\n _rule[attr] = int(val)\n elif attr == 'to_port':\n _rule[attr] = int(val)\n else:\n _rule[attr] = val\n _rules.append(_rule)\n return _rules\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
get_group_id
|
python
|
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
|
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L301-L316
|
[
"def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,\n region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613\n '''\n Get a group object given a name, name and vpc_id/vpc_name or group_id. Return\n a boto.ec2.securitygroup.SecurityGroup object if the group is found, else\n return None.\n '''\n if vpc_name and vpc_id:\n raise SaltInvocationError('The params \\'vpc_id\\' and \\'vpc_name\\' '\n 'are mutually exclusive.')\n if vpc_name:\n try:\n vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile)\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if name:\n if vpc_id is None:\n log.debug('getting group for %s', name)\n group_filter = {'group-name': name}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n # security groups can have the same name if groups exist in both\n # EC2-Classic and EC2-VPC\n # iterate through groups to ensure we return the EC2-Classic\n # security group\n for group in filtered_groups:\n # a group in EC2-Classic will have vpc_id set to None\n if group.vpc_id is None:\n return group\n # If there are more security groups, and no vpc_id, we can't know which one to choose.\n if len(filtered_groups) > 1:\n raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')\n elif len(filtered_groups) == 1:\n return filtered_groups[0]\n return None\n elif vpc_id:\n log.debug('getting group for %s in vpc_id %s', name, vpc_id)\n group_filter = {'group-name': name, 'vpc_id': vpc_id}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n if len(filtered_groups) == 1:\n return filtered_groups[0]\n else:\n return None\n else:\n return None\n elif group_id:\n try:\n groups = conn.get_all_security_groups(group_ids=[group_id])\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if len(groups) == 1:\n return groups[0]\n else:\n return None\n else:\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
convert_to_group_ids
|
python
|
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
|
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L319-L342
|
[
"def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,\n keyid=None, profile=None):\n '''\n Get a Group ID given a Group Name or Group Name and VPC ID\n\n CLI example::\n\n salt myminion boto_secgroup.get_group_id mysecgroup\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n if name.startswith('sg-'):\n log.debug('group %s is a group id. get_group_id not called.', name)\n return name\n group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,\n region=region, key=key, keyid=keyid, profile=profile)\n return getattr(group, 'id', None)\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
get_config
|
python
|
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
|
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L345-L374
|
[
"def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,\n region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613\n '''\n Get a group object given a name, name and vpc_id/vpc_name or group_id. Return\n a boto.ec2.securitygroup.SecurityGroup object if the group is found, else\n return None.\n '''\n if vpc_name and vpc_id:\n raise SaltInvocationError('The params \\'vpc_id\\' and \\'vpc_name\\' '\n 'are mutually exclusive.')\n if vpc_name:\n try:\n vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile)\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if name:\n if vpc_id is None:\n log.debug('getting group for %s', name)\n group_filter = {'group-name': name}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n # security groups can have the same name if groups exist in both\n # EC2-Classic and EC2-VPC\n # iterate through groups to ensure we return the EC2-Classic\n # security group\n for group in filtered_groups:\n # a group in EC2-Classic will have vpc_id set to None\n if group.vpc_id is None:\n return group\n # If there are more security groups, and no vpc_id, we can't know which one to choose.\n if len(filtered_groups) > 1:\n raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')\n elif len(filtered_groups) == 1:\n return filtered_groups[0]\n return None\n elif vpc_id:\n log.debug('getting group for %s in vpc_id %s', name, vpc_id)\n group_filter = {'group-name': name, 'vpc_id': vpc_id}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n if len(filtered_groups) == 1:\n return filtered_groups[0]\n else:\n return None\n else:\n return None\n elif group_id:\n try:\n groups = conn.get_all_security_groups(group_ids=[group_id])\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if len(groups) == 1:\n return groups[0]\n else:\n return None\n else:\n return None\n",
"def _split_rules(rules):\n '''\n Split rules with combined grants into individual rules.\n\n Amazon returns a set of rules with the same protocol, from and to ports\n together as a single rule with a set of grants. Authorizing and revoking\n rules, however, is done as a split set of rules. This function splits the\n rules up.\n '''\n split = []\n for rule in rules:\n ip_protocol = rule.get('ip_protocol')\n to_port = rule.get('to_port')\n from_port = rule.get('from_port')\n grants = rule.get('grants')\n for grant in grants:\n _rule = {'ip_protocol': ip_protocol,\n 'to_port': to_port,\n 'from_port': from_port}\n for key, val in six.iteritems(grant):\n _rule[key] = val\n split.append(_rule)\n return split\n",
"def _parse_rules(sg, rules):\n _rules = []\n for rule in rules:\n log.debug('examining rule %s for group %s', rule, sg.id)\n attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']\n _rule = odict.OrderedDict()\n for attr in attrs:\n val = getattr(rule, attr)\n if not val:\n continue\n if attr == 'grants':\n _grants = []\n for grant in val:\n log.debug('examining grant %s for', grant)\n g_attrs = {'name': 'source_group_name',\n 'owner_id': 'source_group_owner_id',\n 'group_id': 'source_group_group_id',\n 'cidr_ip': 'cidr_ip'}\n _grant = odict.OrderedDict()\n for g_attr, g_attr_map in six.iteritems(g_attrs):\n g_val = getattr(grant, g_attr)\n if not g_val:\n continue\n _grant[g_attr_map] = g_val\n _grants.append(_grant)\n _rule['grants'] = _grants\n elif attr == 'from_port':\n _rule[attr] = int(val)\n elif attr == 'to_port':\n _rule[attr] = int(val)\n else:\n _rule[attr] = val\n _rules.append(_rule)\n return _rules\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
create
|
python
|
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
|
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L377-L403
|
[
"def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,\n profile=None):\n data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile)\n return data.get('id')\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
delete
|
python
|
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
|
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L406-L431
|
[
"def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,\n region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613\n '''\n Get a group object given a name, name and vpc_id/vpc_name or group_id. Return\n a boto.ec2.securitygroup.SecurityGroup object if the group is found, else\n return None.\n '''\n if vpc_name and vpc_id:\n raise SaltInvocationError('The params \\'vpc_id\\' and \\'vpc_name\\' '\n 'are mutually exclusive.')\n if vpc_name:\n try:\n vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile)\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if name:\n if vpc_id is None:\n log.debug('getting group for %s', name)\n group_filter = {'group-name': name}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n # security groups can have the same name if groups exist in both\n # EC2-Classic and EC2-VPC\n # iterate through groups to ensure we return the EC2-Classic\n # security group\n for group in filtered_groups:\n # a group in EC2-Classic will have vpc_id set to None\n if group.vpc_id is None:\n return group\n # If there are more security groups, and no vpc_id, we can't know which one to choose.\n if len(filtered_groups) > 1:\n raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')\n elif len(filtered_groups) == 1:\n return filtered_groups[0]\n return None\n elif vpc_id:\n log.debug('getting group for %s in vpc_id %s', name, vpc_id)\n group_filter = {'group-name': name, 'vpc_id': vpc_id}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n if len(filtered_groups) == 1:\n return filtered_groups[0]\n else:\n return None\n else:\n return None\n elif group_id:\n try:\n groups = conn.get_all_security_groups(group_ids=[group_id])\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if len(groups) == 1:\n return groups[0]\n else:\n return None\n else:\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
authorize
|
python
|
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
|
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L434-L486
|
[
"def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,\n region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613\n '''\n Get a group object given a name, name and vpc_id/vpc_name or group_id. Return\n a boto.ec2.securitygroup.SecurityGroup object if the group is found, else\n return None.\n '''\n if vpc_name and vpc_id:\n raise SaltInvocationError('The params \\'vpc_id\\' and \\'vpc_name\\' '\n 'are mutually exclusive.')\n if vpc_name:\n try:\n vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile)\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if name:\n if vpc_id is None:\n log.debug('getting group for %s', name)\n group_filter = {'group-name': name}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n # security groups can have the same name if groups exist in both\n # EC2-Classic and EC2-VPC\n # iterate through groups to ensure we return the EC2-Classic\n # security group\n for group in filtered_groups:\n # a group in EC2-Classic will have vpc_id set to None\n if group.vpc_id is None:\n return group\n # If there are more security groups, and no vpc_id, we can't know which one to choose.\n if len(filtered_groups) > 1:\n raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')\n elif len(filtered_groups) == 1:\n return filtered_groups[0]\n return None\n elif vpc_id:\n log.debug('getting group for %s in vpc_id %s', name, vpc_id)\n group_filter = {'group-name': name, 'vpc_id': vpc_id}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n if len(filtered_groups) == 1:\n return filtered_groups[0]\n else:\n return None\n else:\n return None\n elif group_id:\n try:\n groups = conn.get_all_security_groups(group_ids=[group_id])\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if len(groups) == 1:\n return groups[0]\n else:\n return None\n else:\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
_find_vpcs
|
python
|
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
|
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L542-L580
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
set_tags
|
python
|
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L583-L644
|
[
"def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,\n region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613\n '''\n Get a group object given a name, name and vpc_id/vpc_name or group_id. Return\n a boto.ec2.securitygroup.SecurityGroup object if the group is found, else\n return None.\n '''\n if vpc_name and vpc_id:\n raise SaltInvocationError('The params \\'vpc_id\\' and \\'vpc_name\\' '\n 'are mutually exclusive.')\n if vpc_name:\n try:\n vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile)\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if name:\n if vpc_id is None:\n log.debug('getting group for %s', name)\n group_filter = {'group-name': name}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n # security groups can have the same name if groups exist in both\n # EC2-Classic and EC2-VPC\n # iterate through groups to ensure we return the EC2-Classic\n # security group\n for group in filtered_groups:\n # a group in EC2-Classic will have vpc_id set to None\n if group.vpc_id is None:\n return group\n # If there are more security groups, and no vpc_id, we can't know which one to choose.\n if len(filtered_groups) > 1:\n raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')\n elif len(filtered_groups) == 1:\n return filtered_groups[0]\n return None\n elif vpc_id:\n log.debug('getting group for %s in vpc_id %s', name, vpc_id)\n group_filter = {'group-name': name, 'vpc_id': vpc_id}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n if len(filtered_groups) == 1:\n return filtered_groups[0]\n else:\n return None\n else:\n return None\n elif group_id:\n try:\n groups = conn.get_all_security_groups(group_ids=[group_id])\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if len(groups) == 1:\n return groups[0]\n else:\n return None\n else:\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/boto_secgroup.py
|
delete_tags
|
python
|
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, list):
tags_to_remove = {}
for tag in tags:
tags_to_remove[tag] = None
secgrp.remove_tags(tags_to_remove)
else:
msg = 'Tags must be a list of tagnames to remove from the security group'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.delete_tags ['TAG_TO_DELETE1','TAG_TO_DELETE2'] security_group_name vpc_id=vpc-13435 profile=my_aws_profile
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L647-L710
|
[
"def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,\n region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613\n '''\n Get a group object given a name, name and vpc_id/vpc_name or group_id. Return\n a boto.ec2.securitygroup.SecurityGroup object if the group is found, else\n return None.\n '''\n if vpc_name and vpc_id:\n raise SaltInvocationError('The params \\'vpc_id\\' and \\'vpc_name\\' '\n 'are mutually exclusive.')\n if vpc_name:\n try:\n vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile)\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if name:\n if vpc_id is None:\n log.debug('getting group for %s', name)\n group_filter = {'group-name': name}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n # security groups can have the same name if groups exist in both\n # EC2-Classic and EC2-VPC\n # iterate through groups to ensure we return the EC2-Classic\n # security group\n for group in filtered_groups:\n # a group in EC2-Classic will have vpc_id set to None\n if group.vpc_id is None:\n return group\n # If there are more security groups, and no vpc_id, we can't know which one to choose.\n if len(filtered_groups) > 1:\n raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')\n elif len(filtered_groups) == 1:\n return filtered_groups[0]\n return None\n elif vpc_id:\n log.debug('getting group for %s in vpc_id %s', name, vpc_id)\n group_filter = {'group-name': name, 'vpc_id': vpc_id}\n filtered_groups = conn.get_all_security_groups(filters=group_filter)\n if len(filtered_groups) == 1:\n return filtered_groups[0]\n else:\n return None\n else:\n return None\n elif group_id:\n try:\n groups = conn.get_all_security_groups(group_ids=[group_id])\n except boto.exception.BotoServerError as e:\n log.debug(e)\n return None\n if len(groups) == 1:\n return groups[0]\n else:\n return None\n else:\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 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 at:
.. code-block:: text
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 or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
secgroup.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
# Import Salt libs
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.utils.odict as odict
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
from salt.ext import six
try:
# pylint: disable=unused-import
import boto
import boto.ec2
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# Boto < 2.4.0 GroupOrCIDR objects have different attributes than
# Boto >= 2.4.0 GroupOrCIDR objects
# Differences include no group_id attribute in Boto < 2.4.0 and returning
# a groupId attribute when a GroupOrCIDR object authorizes an IP range
# Support for Boto < 2.4.0 can be added if needed
has_boto_reqs = salt.utils.versions.check_boto_reqs(
boto_ver='2.4.0',
check_boto3=False
)
if has_boto_reqs is True:
__utils__['boto.assign_funcs'](__name__, 'ec2', pack=__salt__)
return has_boto_reqs
def exists(name=None, region=None, key=None, keyid=None, profile=None,
vpc_id=None, vpc_name=None, group_id=None):
'''
Check to see if a security group exists.
CLI example::
salt myminion boto_secgroup.exists mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
return True
else:
return False
def _vpc_name_to_id(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None,
profile=None):
data = __salt__['boto_vpc.get_id'](name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
return data.get('id')
def _split_rules(rules):
'''
Split rules with combined grants into individual rules.
Amazon returns a set of rules with the same protocol, from and to ports
together as a single rule with a set of grants. Authorizing and revoking
rules, however, is done as a split set of rules. This function splits the
rules up.
'''
split = []
for rule in rules:
ip_protocol = rule.get('ip_protocol')
to_port = rule.get('to_port')
from_port = rule.get('from_port')
grants = rule.get('grants')
for grant in grants:
_rule = {'ip_protocol': ip_protocol,
'to_port': to_port,
'from_port': from_port}
for key, val in six.iteritems(grant):
_rule[key] = val
split.append(_rule)
return split
def _get_group(conn=None, name=None, vpc_id=None, vpc_name=None, group_id=None,
region=None, key=None, keyid=None, profile=None): # pylint: disable=W0613
'''
Get a group object given a name, name and vpc_id/vpc_name or group_id. Return
a boto.ec2.securitygroup.SecurityGroup object if the group is found, else
return None.
'''
if vpc_name and vpc_id:
raise SaltInvocationError('The params \'vpc_id\' and \'vpc_name\' '
'are mutually exclusive.')
if vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if name:
if vpc_id is None:
log.debug('getting group for %s', name)
group_filter = {'group-name': name}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
# security groups can have the same name if groups exist in both
# EC2-Classic and EC2-VPC
# iterate through groups to ensure we return the EC2-Classic
# security group
for group in filtered_groups:
# a group in EC2-Classic will have vpc_id set to None
if group.vpc_id is None:
return group
# If there are more security groups, and no vpc_id, we can't know which one to choose.
if len(filtered_groups) > 1:
raise CommandExecutionError('Security group belongs to more VPCs, specify the VPC ID!')
elif len(filtered_groups) == 1:
return filtered_groups[0]
return None
elif vpc_id:
log.debug('getting group for %s in vpc_id %s', name, vpc_id)
group_filter = {'group-name': name, 'vpc_id': vpc_id}
filtered_groups = conn.get_all_security_groups(filters=group_filter)
if len(filtered_groups) == 1:
return filtered_groups[0]
else:
return None
else:
return None
elif group_id:
try:
groups = conn.get_all_security_groups(group_ids=[group_id])
except boto.exception.BotoServerError as e:
log.debug(e)
return None
if len(groups) == 1:
return groups[0]
else:
return None
else:
return None
def _parse_rules(sg, rules):
_rules = []
for rule in rules:
log.debug('examining rule %s for group %s', rule, sg.id)
attrs = ['ip_protocol', 'from_port', 'to_port', 'grants']
_rule = odict.OrderedDict()
for attr in attrs:
val = getattr(rule, attr)
if not val:
continue
if attr == 'grants':
_grants = []
for grant in val:
log.debug('examining grant %s for', grant)
g_attrs = {'name': 'source_group_name',
'owner_id': 'source_group_owner_id',
'group_id': 'source_group_group_id',
'cidr_ip': 'cidr_ip'}
_grant = odict.OrderedDict()
for g_attr, g_attr_map in six.iteritems(g_attrs):
g_val = getattr(grant, g_attr)
if not g_val:
continue
_grant[g_attr_map] = g_val
_grants.append(_grant)
_rule['grants'] = _grants
elif attr == 'from_port':
_rule[attr] = int(val)
elif attr == 'to_port':
_rule[attr] = int(val)
else:
_rule[attr] = val
_rules.append(_rule)
return _rules
def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filters argument are:
description - The description of the security group.
egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
group-id - The ID of the security group.
group-name - The name of the security group.
ip-permission.cidr - A CIDR range that has been granted permission.
ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
ip-permission.group-id - The ID of a security group that has been granted permission.
ip-permission.group-name - The name of a security group that has been granted permission.
ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
ip-permission.user-id - The ID of an AWS account that has been granted permission.
owner-id - The AWS account ID of the owner of the security group.
tag-key - The key of a tag assigned to the security group.
tag-value - The value of a tag assigned to the security group.
vpc-id - The ID of the VPC specified when the security group was created.
CLI example::
salt myminion boto_secgroup.get_all_security_groups filters='{group-name: mygroup}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if isinstance(groupnames, six.string_types):
groupnames = [groupnames]
if isinstance(group_ids, six.string_types):
groupnames = [group_ids]
interesting = ['description', 'id', 'instances', 'name', 'owner_id',
'region', 'rules', 'rules_egress', 'tags', 'vpc_id']
ret = []
try:
r = conn.get_all_security_groups(groupnames=groupnames,
group_ids=group_ids,
filters=filters)
for g in r:
n = {}
for a in interesting:
v = getattr(g, a, None)
if a == 'region':
v = v.name
elif a in ('rules', 'rules_egress'):
v = _parse_rules(g, v)
elif a == 'instances':
v = [i.id for i in v()]
n[a] = v
ret += [n]
return ret
except boto.exception.BotoServerError as e:
log.debug(e)
return []
def get_group_id(name, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Get a Group ID given a Group Name or Group Name and VPC ID
CLI example::
salt myminion boto_secgroup.get_group_id mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if name.startswith('sg-'):
log.debug('group %s is a group id. get_group_id not called.', name)
return name
group = _get_group(conn=conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile)
return getattr(group, 'id', None)
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Given a list of security groups and a vpc_id, convert_to_group_ids will
convert all list items in the given list to security group ids.
CLI example::
salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
'''
log.debug('security group contents %s pre-conversion', groups)
group_ids = []
for group in groups:
group_id = get_group_id(name=group, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
if not group_id:
# Security groups are a big deal - need to fail if any can't be resolved...
raise CommandExecutionError('Could not resolve Security Group name '
'{0} to a Group ID'.format(group))
else:
group_ids.append(six.text_type(group_id))
log.debug('security group contents %s post-conversion', group_ids)
return group_ids
def get_config(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Get the configuration for a security group.
CLI example::
salt myminion boto_secgroup.get_config mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
sg = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if sg:
ret = odict.OrderedDict()
ret['name'] = sg.name
# TODO: add support for vpc_id in return
# ret['vpc_id'] = sg.vpc_id
ret['group_id'] = sg.id
ret['owner_id'] = sg.owner_id
ret['description'] = sg.description
ret['tags'] = sg.tags
_rules = _parse_rules(sg, sg.rules)
_rules_egress = _parse_rules(sg, sg.rules_egress)
ret['rules'] = _split_rules(_rules)
ret['rules_egress'] = _split_rules(_rules_egress)
return ret
else:
return None
def create(name, description, vpc_id=None, vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Create a security group.
CLI example::
salt myminion boto_secgroup.create mysecgroup 'My Security Group'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not vpc_id and vpc_name:
try:
vpc_id = _vpc_name_to_id(vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
except boto.exception.BotoServerError as e:
log.debug(e)
return False
created = conn.create_security_group(name, description, vpc_id)
if created:
log.info('Created security group %s.', name)
return True
else:
msg = 'Failed to create security group {0}.'.format(name)
log.error(msg)
return False
def delete(name=None, group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None):
'''
Delete a security group.
CLI example::
salt myminion boto_secgroup.delete mysecgroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
deleted = conn.delete_security_group(group_id=group.id)
if deleted:
log.info('Deleted security group %s with id %s.', group.name, group.id)
return True
else:
msg = 'Failed to delete security group {0}.'.format(name)
log.error(msg)
return False
else:
log.debug('Security group not found.')
return False
def authorize(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Add a new rule to an existing security group.
CLI example::
salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
added = None
if not egress:
added = conn.authorize_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
added = conn.authorize_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if added:
log.info('Added rule to security group %s with id %s',
group.name, group.id)
return True
else:
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
# if we are trying to add the same rule then we are already in the desired state, return true
if e.error_code == 'InvalidPermission.Duplicate':
return True
msg = ('Failed to add rule to security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to add rule to security group.')
return False
def revoke(name=None, source_group_name=None,
source_group_owner_id=None, ip_protocol=None,
from_port=None, to_port=None, cidr_ip=None, group_id=None,
source_group_group_id=None, region=None, key=None, keyid=None,
profile=None, vpc_id=None, vpc_name=None, egress=False):
'''
Remove a rule from an existing security group.
CLI example::
salt myminion boto_secgroup.revoke mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='10.0.0.0/8'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if group:
try:
revoked = None
if not egress:
revoked = conn.revoke_security_group(
src_security_group_name=source_group_name,
src_security_group_owner_id=source_group_owner_id,
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_security_group_group_id=source_group_group_id)
else:
revoked = conn.revoke_security_group_egress(
ip_protocol=ip_protocol, from_port=from_port, to_port=to_port,
cidr_ip=cidr_ip, group_id=group.id,
src_group_id=source_group_group_id)
if revoked:
log.info('Removed rule from security group %s with id %s.',
group.name, group.id)
return True
else:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
return False
except boto.exception.EC2ResponseError as e:
msg = ('Failed to remove rule from security group {0} with id {1}.'
.format(group.name, group.id))
log.error(msg)
log.error(e)
return False
else:
log.error('Failed to remove rule from security group.')
return False
def _find_vpcs(vpc_id=None, vpc_name=None, cidr=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given VPC properties, find and return matching VPC ids.
Borrowed from boto_vpc; these could be refactored into a common library
'''
if all((vpc_id, vpc_name)):
raise SaltInvocationError('Only one of vpc_name or vpc_id may be '
'provided.')
if not any((vpc_id, vpc_name, tags, cidr)):
raise SaltInvocationError('At least one of the following must be '
'provided: vpc_id, vpc_name, cidr or tags.')
local_get_conn = __utils__['boto.get_connection_func']('vpc')
conn = local_get_conn(region=region, key=key, keyid=keyid, profile=profile)
filter_parameters = {'filters': {}}
if vpc_id:
filter_parameters['vpc_ids'] = [vpc_id]
if cidr:
filter_parameters['filters']['cidr'] = cidr
if vpc_name:
filter_parameters['filters']['tag:Name'] = vpc_name
if tags:
for tag_name, tag_value in six.iteritems(tags):
filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value
vpcs = conn.get_all_vpcs(**filter_parameters)
log.debug('The filters criteria %s matched the following VPCs:%s',
filter_parameters, vpcs)
if vpcs:
return [vpc.id for vpc in vpcs]
else:
return []
def set_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
sets tags on a security group
.. versionadded:: 2016.3.0
tags
a dict of key:value pair of tags to set on the security group
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
vpc_id
the id of the vpc, in lieu of the vpc_name
region
the amazon region
key
amazon key
keyid
amazon keyid
profile
amazon profile
CLI example:
.. code-block:: bash
salt myminion boto_secgroup.set_tags "{'TAG1': 'Value1', 'TAG2': 'Value2'}" security_group_name vpc_id=vpc-13435 profile=my_aws_profile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
secgrp = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
group_id=group_id, region=region, key=key, keyid=keyid,
profile=profile)
if secgrp:
if isinstance(tags, dict):
secgrp.add_tags(tags)
else:
msg = 'Tags must be a dict of tagname:tagvalue'
raise SaltInvocationError(msg)
else:
msg = 'The security group could not be found'
raise SaltInvocationError(msg)
return True
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
list_upgrades
|
python
|
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
|
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L455-L487
|
[
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
info_available
|
python
|
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
|
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L554-L613
|
[
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
version_cmp
|
python
|
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
|
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L707-L726
| null |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
list_pkgs
|
python
|
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
|
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L729-L858
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def split_input(val, mapper=None):\n '''\n Take an input value and split it into a list, returning the resulting list\n '''\n if mapper is None:\n mapper = lambda x: x\n if isinstance(val, list):\n return list(map(mapper, val))\n try:\n return list(map(mapper, [x.strip() for x in val.split(',')]))\n except AttributeError:\n return list(map(mapper, [x.strip() for x in six.text_type(val).split(',')]))\n",
"def parse_pkginfo(line, osarch=None):\n '''\n A small helper to parse an rpm/repoquery command's output. Returns a\n pkginfo namedtuple.\n '''\n try:\n name, epoch, version, release, arch, repoid, install_time = line.split('_|-')\n # Handle unpack errors (should never happen with the queryformat we are\n # using, but can't hurt to be careful).\n except ValueError:\n return None\n\n name = resolve_name(name, arch, osarch)\n if release:\n version += '-{0}'.format(release)\n if epoch not in ('(none)', '0'):\n version = ':'.join((epoch, version))\n\n if install_time not in ('(none)', '0'):\n install_date = datetime.datetime.utcfromtimestamp(int(install_time)).isoformat() + \"Z\"\n install_date_time_t = int(install_time)\n else:\n install_date = None\n install_date_time_t = None\n\n return pkginfo(name, version, arch, repoid, install_date, install_date_time_t)\n",
"def info_available(*names, **kwargs):\n '''\n Return the information of the named package available for the system.\n\n refresh\n force a refresh if set to True (default).\n If set to False it depends on zypper if a refresh is\n executed or not.\n\n root\n operate on a different root directory.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' pkg.info_available <package1>\n salt '*' pkg.info_available <package1> <package2> <package3> ...\n '''\n ret = {}\n\n if not names:\n return ret\n else:\n names = sorted(list(set(names)))\n\n root = kwargs.get('root', None)\n\n # Refresh db before extracting the latest package\n if kwargs.get('refresh', True):\n refresh_db(root)\n\n pkg_info = []\n batch = names[:]\n batch_size = 200\n\n # Run in batches\n while batch:\n pkg_info.extend(re.split(r\"Information for package*\",\n __zypper__(root=root).nolock.call('info', '-t', 'package',\n *batch[:batch_size])))\n batch = batch[batch_size:]\n\n for pkg_data in pkg_info:\n nfo = {}\n for line in [data for data in pkg_data.split('\\n') if ':' in data]:\n if line.startswith('-----'):\n continue\n kw = [data.strip() for data in line.split(':', 1)]\n if len(kw) == 2 and kw[1]:\n nfo[kw[0].lower()] = kw[1]\n if nfo.get('name'):\n name = nfo.pop('name')\n ret[name] = nfo\n if nfo.get('status'):\n nfo['status'] = nfo.get('status')\n if nfo.get('installed'):\n nfo['installed'] = nfo.get('installed').lower().startswith('yes')\n\n return ret\n",
"def list_installed_patches(root=None, **kwargs):\n '''\n .. versionadded:: 2017.7.0\n\n List installed advisory patches on the system.\n\n root\n operate on a different root directory.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.list_installed_patches\n '''\n return _get_patches(installed_only=True, root=root)\n",
"def list_installed_patterns(root=None):\n '''\n List installed patterns on the system.\n\n root\n operate on a different root directory.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.list_installed_patterns\n '''\n return _get_patterns(installed_only=True, root=root)\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
list_repo_pkgs
|
python
|
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
|
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L861-L979
| null |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_get_configured_repos
|
python
|
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
|
Get all the info about repositories from the configurations.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L982-L994
| null |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_get_repo_info
|
python
|
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
|
Get one repo meta-data.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L997-L1011
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _get_configured_repos(root=None):\n '''\n Get all the info about repositories from the configurations.\n '''\n\n repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS\n repos_cfg = configparser.ConfigParser()\n if os.path.exists(repos):\n repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(\".repo\")])\n else:\n log.warning('Repositories not found in %s', repos)\n\n return repos_cfg\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
list_repos
|
python
|
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
|
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1030-L1048
|
[
"def _get_configured_repos(root=None):\n '''\n Get all the info about repositories from the configurations.\n '''\n\n repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS\n repos_cfg = configparser.ConfigParser()\n if os.path.exists(repos):\n repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(\".repo\")])\n else:\n log.warning('Repositories not found in %s', repos)\n\n return repos_cfg\n",
"def _get_repo_info(alias, repos_cfg=None, root=None):\n '''\n Get one repo meta-data.\n '''\n try:\n meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))\n meta['alias'] = alias\n for key, val in six.iteritems(meta):\n if val in ['0', '1']:\n meta[key] = int(meta[key]) == 1\n elif val == 'NONE':\n meta[key] = None\n return meta\n except (ValueError, configparser.NoSectionError):\n return {}\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
del_repo
|
python
|
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
|
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1051-L1075
|
[
"def _get_configured_repos(root=None):\n '''\n Get all the info about repositories from the configurations.\n '''\n\n repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS\n repos_cfg = configparser.ConfigParser()\n if os.path.exists(repos):\n repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(\".repo\")])\n else:\n log.warning('Repositories not found in %s', repos)\n\n return repos_cfg\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
mod_repo
|
python
|
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
|
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1078-L1233
|
[
"def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument\n '''\n Display a repo.\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.get_repo alias\n '''\n return _get_repo_info(repo, root=root)\n",
"def del_repo(repo, root=None):\n '''\n Delete a repo.\n\n root\n operate on a different root directory.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.del_repo alias\n '''\n repos_cfg = _get_configured_repos(root=root)\n for alias in repos_cfg.sections():\n if alias == repo:\n doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)\n msg = doc.getElementsByTagName('message')\n if doc.getElementsByTagName('progress') and msg:\n return {\n repo: True,\n 'message': msg[0].childNodes[0].nodeValue,\n }\n\n raise CommandExecutionError('Repository \\'{0}\\' not found.'.format(repo))\n",
"def mod_repo(repo, **kwargs):\n '''\n Modify one or more values for a repo. If the repo does not exist, it will\n be created, so long as the following values are specified:\n\n repo or alias\n alias by which Zypper refers to the repo\n\n url, mirrorlist or baseurl\n the URL for Zypper to reference\n\n enabled\n Enable or disable (True or False) repository,\n but do not remove if disabled.\n\n refresh\n Enable or disable (True or False) auto-refresh of the repository.\n\n cache\n Enable or disable (True or False) RPM files caching.\n\n gpgcheck\n Enable or disable (True or False) GPG check for this repository.\n\n gpgautoimport : False\n If set to True, automatically trust and import public GPG key for\n the repository.\n\n root\n operate on a different root directory.\n\n Key/Value pairs may also be removed from a repo's configuration by setting\n a key to a blank value. Bear in mind that a name cannot be deleted, and a\n URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.mod_repo alias alias=new_alias\n salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/\n '''\n\n root = kwargs.get('root') or None\n repos_cfg = _get_configured_repos(root=root)\n added = False\n\n # An attempt to add new one?\n if repo not in repos_cfg.sections():\n url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))\n if not url:\n raise CommandExecutionError(\n 'Repository \\'{0}\\' not found, and neither \\'baseurl\\' nor '\n '\\'mirrorlist\\' was specified'.format(repo)\n )\n\n if not _urlparse(url).scheme:\n raise CommandExecutionError(\n 'Repository \\'{0}\\' not found and URL for baseurl/mirrorlist '\n 'is malformed'.format(repo)\n )\n\n # Is there already such repo under different alias?\n for alias in repos_cfg.sections():\n repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)\n\n # Complete user URL, in case it is not\n new_url = _urlparse(url)\n if not new_url.path:\n new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123\n netloc=new_url.netloc,\n path='/',\n params=new_url.params,\n query=new_url.query,\n fragment=new_url.fragment)\n base_url = _urlparse(repo_meta['baseurl'])\n\n if new_url == base_url:\n raise CommandExecutionError(\n 'Repository \\'{0}\\' already exists as \\'{1}\\'.'.format(\n repo,\n alias\n )\n )\n\n # Add new repo\n __zypper__(root=root).xml.call('ar', url, repo)\n\n # Verify the repository has been added\n repos_cfg = _get_configured_repos(root=root)\n if repo not in repos_cfg.sections():\n raise CommandExecutionError(\n 'Failed add new repository \\'{0}\\' for unspecified reason. '\n 'Please check zypper logs.'.format(repo))\n added = True\n\n repo_info = _get_repo_info(repo, root=root)\n if (\n not added and 'baseurl' in kwargs and\n not (kwargs['baseurl'] == repo_info['baseurl'])\n ):\n # Note: zypper does not support changing the baseurl\n # we need to remove the repository and add it again with the new baseurl\n repo_info.update(kwargs)\n repo_info.setdefault('cache', False)\n del_repo(repo, root=root)\n return mod_repo(repo, root=root, **repo_info)\n\n # Modify added or existing repo according to the options\n cmd_opt = []\n global_cmd_opt = []\n call_refresh = False\n\n if 'enabled' in kwargs:\n cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')\n\n if 'refresh' in kwargs:\n cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')\n\n if 'cache' in kwargs:\n cmd_opt.append(\n kwargs['cache'] and '--keep-packages' or '--no-keep-packages'\n )\n\n if 'gpgcheck' in kwargs:\n cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')\n\n if 'priority' in kwargs:\n cmd_opt.append(\"--priority={0}\".format(kwargs.get('priority', DEFAULT_PRIORITY)))\n\n if 'humanname' in kwargs:\n cmd_opt.append(\"--name='{0}'\".format(kwargs.get('humanname')))\n\n if kwargs.get('gpgautoimport') is True:\n global_cmd_opt.append('--gpg-auto-import-keys')\n call_refresh = True\n\n if cmd_opt:\n cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]\n __zypper__(root=root).refreshable.xml.call(*cmd_opt)\n\n comment = None\n if call_refresh:\n # when used with \"zypper ar --refresh\" or \"zypper mr --refresh\"\n # --gpg-auto-import-keys is not doing anything\n # so we need to specifically refresh here with --gpg-auto-import-keys\n refresh_opts = global_cmd_opt + ['refresh'] + [repo]\n __zypper__(root=root).xml.call(*refresh_opts)\n elif not added and not cmd_opt:\n comment = 'Specified arguments did not result in modification of repo'\n\n repo = get_repo(repo, root=root)\n if comment:\n repo['comment'] = comment\n\n return repo\n",
"def _get_configured_repos(root=None):\n '''\n Get all the info about repositories from the configurations.\n '''\n\n repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS\n repos_cfg = configparser.ConfigParser()\n if os.path.exists(repos):\n repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(\".repo\")])\n else:\n log.warning('Repositories not found in %s', repos)\n\n return repos_cfg\n",
"def _get_repo_info(alias, repos_cfg=None, root=None):\n '''\n Get one repo meta-data.\n '''\n try:\n meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))\n meta['alias'] = alias\n for key, val in six.iteritems(meta):\n if val in ['0', '1']:\n meta[key] = int(meta[key]) == 1\n elif val == 'NONE':\n meta[key] = None\n return meta\n except (ValueError, configparser.NoSectionError):\n return {}\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
refresh_db
|
python
|
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
|
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1236-L1270
|
[
"def clear_rtag(opts):\n '''\n Remove the rtag file\n '''\n try:\n os.remove(rtag(opts))\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n # Using __str__() here to get the fully-formatted error message\n # (error number, error message, path)\n log.warning('Encountered error removing rtag: %s', exc.__str__())\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_find_types
|
python
|
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
|
Form a package names list, find prefixes of packages types.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1273-L1276
| null |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
install
|
python
|
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
|
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1279-L1528
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def split_comparison(version):\n match = re.match(r'^(<=>|!=|>=|<=|>>|<<|<>|>|<|=)?\\s?([^<>=]+)$', version)\n if match:\n comparison = match.group(1) or ''\n version = match.group(2)\n else:\n comparison = ''\n return comparison, version\n",
"def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):\n '''\n List the packages currently installed as a dict. By default, the dict\n contains versions as a comma separated string::\n\n {'<package_name>': '<version>[,<version>...]'}\n\n versions_as_list:\n If set to true, the versions are provided as a list\n\n {'<package_name>': ['<version>', '<version>']}\n\n root:\n operate on a different root directory.\n\n includes:\n List of types of packages to include (package, patch, pattern, product)\n By default packages are always included\n\n attr:\n If a list of package attributes is specified, returned value will\n contain them in addition to version, eg.::\n\n {'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}\n\n Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,\n ``install_date``, ``install_date_time_t``.\n\n If ``all`` is specified, all valid attributes will be returned.\n\n .. versionadded:: 2018.3.0\n\n removed:\n not supported\n\n purge_desired:\n not supported\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs attr=version,arch\n salt '*' pkg.list_pkgs attr='[\"version\", \"arch\"]'\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n attr = kwargs.get('attr')\n if attr is not None:\n attr = salt.utils.args.split_input(attr)\n\n includes = includes if includes else []\n\n contextkey = 'pkg.list_pkgs'\n\n # TODO(aplanas): this cached value depends on the parameters\n if contextkey not in __context__:\n ret = {}\n cmd = ['rpm']\n if root:\n cmd.extend(['--root', root])\n cmd.extend(['-qa', '--queryformat',\n salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\\n'])\n output = __salt__['cmd.run'](cmd,\n python_shell=False,\n output_loglevel='trace')\n for line in output.splitlines():\n pkginfo = salt.utils.pkg.rpm.parse_pkginfo(\n line,\n osarch=__grains__['osarch']\n )\n if pkginfo:\n # see rpm version string rules available at https://goo.gl/UGKPNd\n pkgver = pkginfo.version\n epoch = ''\n release = ''\n if ':' in pkgver:\n epoch, pkgver = pkgver.split(\":\", 1)\n if '-' in pkgver:\n pkgver, release = pkgver.split(\"-\", 1)\n all_attr = {\n 'epoch': epoch,\n 'version': pkgver,\n 'release': release,\n 'arch': pkginfo.arch,\n 'install_date': pkginfo.install_date,\n 'install_date_time_t': pkginfo.install_date_time_t\n }\n __salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)\n\n _ret = {}\n for pkgname in ret:\n # Filter out GPG public keys packages\n if pkgname.startswith('gpg-pubkey'):\n continue\n _ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])\n\n for include in includes:\n if include in ('pattern', 'patch'):\n if include == 'pattern':\n pkgs = list_installed_patterns(root=root)\n elif include == 'patch':\n pkgs = list_installed_patches(root=root)\n else:\n pkgs = []\n for pkg in pkgs:\n pkg_extended_name = '{}:{}'.format(include, pkg)\n info = info_available(pkg_extended_name,\n refresh=False,\n root=root)\n _ret[pkg_extended_name] = [{\n 'epoch': None,\n 'version': info[pkg]['version'],\n 'release': None,\n 'arch': info[pkg]['arch'],\n 'install_date': None,\n 'install_date_time_t': None,\n }]\n\n __context__[contextkey] = _ret\n\n return __salt__['pkg_resource.format_pkg_list'](\n __context__[contextkey],\n versions_as_list,\n attr)\n",
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n",
"def list_patches(refresh=False, root=None, **kwargs):\n '''\n .. versionadded:: 2017.7.0\n\n List all known advisory patches from available repos.\n\n refresh\n force a refresh if set to True.\n If set to False (default) it depends on zypper if a refresh is\n executed.\n\n root\n operate on a different root directory.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.list_patches\n '''\n if refresh:\n refresh_db(root)\n\n return _get_patches(root=root)\n",
"def list_downloaded(root=None):\n '''\n .. versionadded:: 2017.7.0\n\n List prefetched packages downloaded by Zypper in the local disk.\n\n root\n operate on a different root directory.\n\n CLI example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_downloaded\n '''\n CACHE_DIR = '/var/cache/zypp/packages/'\n if root:\n CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))\n\n ret = {}\n for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):\n for filename in fnmatch.filter(filenames, '*.rpm'):\n package_path = os.path.join(root, filename)\n pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)\n pkg_timestamp = int(os.path.getctime(package_path))\n ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {\n 'path': package_path,\n 'size': os.path.getsize(package_path),\n 'creation_date_time_t': pkg_timestamp,\n 'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),\n }\n return ret\n",
"def _systemd_scope():\n return salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True)\n",
"def _clean_cache():\n '''\n Clean cached results\n '''\n for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:\n __context__.pop(cache_name, None)\n",
"def _find_types(pkgs):\n '''Form a package names list, find prefixes of packages types.'''\n return sorted({pkg.split(':', 1)[0] for pkg in pkgs\n if len(pkg.split(':', 1)) == 2})\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
upgrade
|
python
|
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
|
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1531-L1656
|
[
"def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):\n '''\n List the packages currently installed as a dict. By default, the dict\n contains versions as a comma separated string::\n\n {'<package_name>': '<version>[,<version>...]'}\n\n versions_as_list:\n If set to true, the versions are provided as a list\n\n {'<package_name>': ['<version>', '<version>']}\n\n root:\n operate on a different root directory.\n\n includes:\n List of types of packages to include (package, patch, pattern, product)\n By default packages are always included\n\n attr:\n If a list of package attributes is specified, returned value will\n contain them in addition to version, eg.::\n\n {'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}\n\n Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,\n ``install_date``, ``install_date_time_t``.\n\n If ``all`` is specified, all valid attributes will be returned.\n\n .. versionadded:: 2018.3.0\n\n removed:\n not supported\n\n purge_desired:\n not supported\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs attr=version,arch\n salt '*' pkg.list_pkgs attr='[\"version\", \"arch\"]'\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n attr = kwargs.get('attr')\n if attr is not None:\n attr = salt.utils.args.split_input(attr)\n\n includes = includes if includes else []\n\n contextkey = 'pkg.list_pkgs'\n\n # TODO(aplanas): this cached value depends on the parameters\n if contextkey not in __context__:\n ret = {}\n cmd = ['rpm']\n if root:\n cmd.extend(['--root', root])\n cmd.extend(['-qa', '--queryformat',\n salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\\n'])\n output = __salt__['cmd.run'](cmd,\n python_shell=False,\n output_loglevel='trace')\n for line in output.splitlines():\n pkginfo = salt.utils.pkg.rpm.parse_pkginfo(\n line,\n osarch=__grains__['osarch']\n )\n if pkginfo:\n # see rpm version string rules available at https://goo.gl/UGKPNd\n pkgver = pkginfo.version\n epoch = ''\n release = ''\n if ':' in pkgver:\n epoch, pkgver = pkgver.split(\":\", 1)\n if '-' in pkgver:\n pkgver, release = pkgver.split(\"-\", 1)\n all_attr = {\n 'epoch': epoch,\n 'version': pkgver,\n 'release': release,\n 'arch': pkginfo.arch,\n 'install_date': pkginfo.install_date,\n 'install_date_time_t': pkginfo.install_date_time_t\n }\n __salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)\n\n _ret = {}\n for pkgname in ret:\n # Filter out GPG public keys packages\n if pkgname.startswith('gpg-pubkey'):\n continue\n _ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])\n\n for include in includes:\n if include in ('pattern', 'patch'):\n if include == 'pattern':\n pkgs = list_installed_patterns(root=root)\n elif include == 'patch':\n pkgs = list_installed_patches(root=root)\n else:\n pkgs = []\n for pkg in pkgs:\n pkg_extended_name = '{}:{}'.format(include, pkg)\n info = info_available(pkg_extended_name,\n refresh=False,\n root=root)\n _ret[pkg_extended_name] = [{\n 'epoch': None,\n 'version': info[pkg]['version'],\n 'release': None,\n 'arch': info[pkg]['arch'],\n 'install_date': None,\n 'install_date_time_t': None,\n }]\n\n __context__[contextkey] = _ret\n\n return __salt__['pkg_resource.format_pkg_list'](\n __context__[contextkey],\n versions_as_list,\n attr)\n",
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n",
"def _systemd_scope():\n return salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True)\n",
"def _clean_cache():\n '''\n Clean cached results\n '''\n for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:\n __context__.pop(cache_name, None)\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_uninstall
|
python
|
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
|
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1659-L1699
|
[
"def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):\n '''\n List the packages currently installed as a dict. By default, the dict\n contains versions as a comma separated string::\n\n {'<package_name>': '<version>[,<version>...]'}\n\n versions_as_list:\n If set to true, the versions are provided as a list\n\n {'<package_name>': ['<version>', '<version>']}\n\n root:\n operate on a different root directory.\n\n includes:\n List of types of packages to include (package, patch, pattern, product)\n By default packages are always included\n\n attr:\n If a list of package attributes is specified, returned value will\n contain them in addition to version, eg.::\n\n {'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}\n\n Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,\n ``install_date``, ``install_date_time_t``.\n\n If ``all`` is specified, all valid attributes will be returned.\n\n .. versionadded:: 2018.3.0\n\n removed:\n not supported\n\n purge_desired:\n not supported\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs attr=version,arch\n salt '*' pkg.list_pkgs attr='[\"version\", \"arch\"]'\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n attr = kwargs.get('attr')\n if attr is not None:\n attr = salt.utils.args.split_input(attr)\n\n includes = includes if includes else []\n\n contextkey = 'pkg.list_pkgs'\n\n # TODO(aplanas): this cached value depends on the parameters\n if contextkey not in __context__:\n ret = {}\n cmd = ['rpm']\n if root:\n cmd.extend(['--root', root])\n cmd.extend(['-qa', '--queryformat',\n salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\\n'])\n output = __salt__['cmd.run'](cmd,\n python_shell=False,\n output_loglevel='trace')\n for line in output.splitlines():\n pkginfo = salt.utils.pkg.rpm.parse_pkginfo(\n line,\n osarch=__grains__['osarch']\n )\n if pkginfo:\n # see rpm version string rules available at https://goo.gl/UGKPNd\n pkgver = pkginfo.version\n epoch = ''\n release = ''\n if ':' in pkgver:\n epoch, pkgver = pkgver.split(\":\", 1)\n if '-' in pkgver:\n pkgver, release = pkgver.split(\"-\", 1)\n all_attr = {\n 'epoch': epoch,\n 'version': pkgver,\n 'release': release,\n 'arch': pkginfo.arch,\n 'install_date': pkginfo.install_date,\n 'install_date_time_t': pkginfo.install_date_time_t\n }\n __salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)\n\n _ret = {}\n for pkgname in ret:\n # Filter out GPG public keys packages\n if pkgname.startswith('gpg-pubkey'):\n continue\n _ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])\n\n for include in includes:\n if include in ('pattern', 'patch'):\n if include == 'pattern':\n pkgs = list_installed_patterns(root=root)\n elif include == 'patch':\n pkgs = list_installed_patches(root=root)\n else:\n pkgs = []\n for pkg in pkgs:\n pkg_extended_name = '{}:{}'.format(include, pkg)\n info = info_available(pkg_extended_name,\n refresh=False,\n root=root)\n _ret[pkg_extended_name] = [{\n 'epoch': None,\n 'version': info[pkg]['version'],\n 'release': None,\n 'arch': info[pkg]['arch'],\n 'install_date': None,\n 'install_date_time_t': None,\n }]\n\n __context__[contextkey] = _ret\n\n return __salt__['pkg_resource.format_pkg_list'](\n __context__[contextkey],\n versions_as_list,\n attr)\n",
"def _systemd_scope():\n return salt.utils.systemd.has_scope(__context__) \\\n and __salt__['config.get']('systemd.scope', True)\n",
"def _clean_cache():\n '''\n Clean cached results\n '''\n for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:\n __context__.pop(cache_name, None)\n",
"def _find_types(pkgs):\n '''Form a package names list, find prefixes of packages types.'''\n return sorted({pkg.split(':', 1)[0] for pkg in pkgs\n if len(pkg.split(':', 1)) == 2})\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
remove
|
python
|
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
|
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1728-L1772
|
[
"def _uninstall(name=None, pkgs=None, root=None):\n '''\n Remove and purge do identical things but with different Zypper commands,\n this function performs the common logic.\n '''\n try:\n pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]\n except MinionError as exc:\n raise CommandExecutionError(exc)\n\n includes = _find_types(pkg_params.keys())\n old = list_pkgs(root=root, includes=includes)\n targets = []\n for target in pkg_params:\n # Check if package version set to be removed is actually installed:\n # old[target] contains a comma-separated list of installed versions\n if target in old and pkg_params[target] in old[target].split(','):\n targets.append(target + \"-\" + pkg_params[target])\n elif target in old and not pkg_params[target]:\n targets.append(target)\n if not targets:\n return {}\n\n systemd_scope = _systemd_scope()\n\n errors = []\n while targets:\n __zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])\n targets = targets[500:]\n\n _clean_cache()\n new = list_pkgs(root=root, includes=includes)\n ret = salt.utils.data.compare_dicts(old, new)\n\n if errors:\n raise CommandExecutionError(\n 'Problem encountered removing package(s)',\n info={'errors': errors, 'changes': ret}\n )\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
purge
|
python
|
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
|
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1775-L1820
|
[
"def _uninstall(name=None, pkgs=None, root=None):\n '''\n Remove and purge do identical things but with different Zypper commands,\n this function performs the common logic.\n '''\n try:\n pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]\n except MinionError as exc:\n raise CommandExecutionError(exc)\n\n includes = _find_types(pkg_params.keys())\n old = list_pkgs(root=root, includes=includes)\n targets = []\n for target in pkg_params:\n # Check if package version set to be removed is actually installed:\n # old[target] contains a comma-separated list of installed versions\n if target in old and pkg_params[target] in old[target].split(','):\n targets.append(target + \"-\" + pkg_params[target])\n elif target in old and not pkg_params[target]:\n targets.append(target)\n if not targets:\n return {}\n\n systemd_scope = _systemd_scope()\n\n errors = []\n while targets:\n __zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])\n targets = targets[500:]\n\n _clean_cache()\n new = list_pkgs(root=root, includes=includes)\n ret = salt.utils.data.compare_dicts(old, new)\n\n if errors:\n raise CommandExecutionError(\n 'Problem encountered removing package(s)',\n info={'errors': errors, 'changes': ret}\n )\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
list_locks
|
python
|
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
|
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1823-L1859
|
[
"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_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else 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 exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, 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 or bytearray')\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
clean_locks
|
python
|
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
|
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1862-L1888
| null |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
unhold
|
python
|
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
|
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1891-L1932
|
[
"def list_locks(root=None):\n '''\n List current package locks.\n\n root\n operate on a different root directory.\n\n Return a dict containing the locked package with attributes::\n\n {'<package>': {'case_sensitive': '<case_sensitive>',\n 'match_type': '<match_type>'\n 'type': '<type>'}}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_locks\n '''\n locks = {}\n _locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS\n try:\n with salt.utils.files.fopen(_locks) as fhr:\n items = salt.utils.stringutils.to_unicode(fhr.read()).split('\\n\\n')\n for meta in [item.split('\\n') for item in items]:\n lock = {}\n for element in [el for el in meta if el]:\n if ':' in element:\n lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))\n if lock.get('solvable_name'):\n locks[lock.pop('solvable_name')] = lock\n except IOError:\n pass\n except Exception:\n log.warning('Detected a problem when accessing %s', _locks)\n\n return locks\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
remove_lock
|
python
|
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
|
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1935-L1968
|
[
"def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n",
"def list_locks(root=None):\n '''\n List current package locks.\n\n root\n operate on a different root directory.\n\n Return a dict containing the locked package with attributes::\n\n {'<package>': {'case_sensitive': '<case_sensitive>',\n 'match_type': '<match_type>'\n 'type': '<type>'}}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_locks\n '''\n locks = {}\n _locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS\n try:\n with salt.utils.files.fopen(_locks) as fhr:\n items = salt.utils.stringutils.to_unicode(fhr.read()).split('\\n\\n')\n for meta in [item.split('\\n') for item in items]:\n lock = {}\n for element in [el for el in meta if el]:\n if ':' in element:\n lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))\n if lock.get('solvable_name'):\n locks[lock.pop('solvable_name')] = lock\n except IOError:\n pass\n except Exception:\n log.warning('Detected a problem when accessing %s', _locks)\n\n return locks\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
hold
|
python
|
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
|
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L1971-L2016
|
[
"def list_locks(root=None):\n '''\n List current package locks.\n\n root\n operate on a different root directory.\n\n Return a dict containing the locked package with attributes::\n\n {'<package>': {'case_sensitive': '<case_sensitive>',\n 'match_type': '<match_type>'\n 'type': '<type>'}}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_locks\n '''\n locks = {}\n _locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS\n try:\n with salt.utils.files.fopen(_locks) as fhr:\n items = salt.utils.stringutils.to_unicode(fhr.read()).split('\\n\\n')\n for meta in [item.split('\\n') for item in items]:\n lock = {}\n for element in [el for el in meta if el]:\n if ':' in element:\n lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))\n if lock.get('solvable_name'):\n locks[lock.pop('solvable_name')] = lock\n except IOError:\n pass\n except Exception:\n log.warning('Detected a problem when accessing %s', _locks)\n\n return locks\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
add_lock
|
python
|
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
|
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2019-L2049
|
[
"def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n",
"def list_locks(root=None):\n '''\n List current package locks.\n\n root\n operate on a different root directory.\n\n Return a dict containing the locked package with attributes::\n\n {'<package>': {'case_sensitive': '<case_sensitive>',\n 'match_type': '<match_type>'\n 'type': '<type>'}}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_locks\n '''\n locks = {}\n _locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS\n try:\n with salt.utils.files.fopen(_locks) as fhr:\n items = salt.utils.stringutils.to_unicode(fhr.read()).split('\\n\\n')\n for meta in [item.split('\\n') for item in items]:\n lock = {}\n for element in [el for el in meta if el]:\n if ':' in element:\n lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))\n if lock.get('solvable_name'):\n locks[lock.pop('solvable_name')] = lock\n except IOError:\n pass\n except Exception:\n log.warning('Detected a problem when accessing %s', _locks)\n\n return locks\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_get_patterns
|
python
|
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
|
List all known patterns in repos.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2185-L2198
| null |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
list_patterns
|
python
|
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
|
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2201-L2222
|
[
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n",
"def _get_patterns(installed_only=None, root=None):\n '''\n List all known patterns in repos.\n '''\n patterns = {}\n for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):\n installed = element.getAttribute('status') == 'installed'\n if (installed_only and installed) or not installed_only:\n patterns[element.getAttribute('name')] = {\n 'installed': installed,\n 'summary': element.getAttribute('summary'),\n }\n\n return patterns\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
search
|
python
|
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
|
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2241-L2345
|
[
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_get_first_aggregate_text
|
python
|
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
|
Extract text from the first occurred DOM aggregate.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2348-L2359
| null |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
list_products
|
python
|
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
|
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2362-L2431
|
[
"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_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else 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 exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, 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 or bytearray')\n",
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n",
"def _get_first_aggregate_text(node_list):\n '''\n Extract text from the first occurred DOM aggregate.\n '''\n if not node_list:\n return ''\n\n out = []\n for node in node_list[0].childNodes:\n if node.nodeType == dom.Document.TEXT_NODE:\n out.append(node.nodeValue)\n return '\\n'.join(out)\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
download
|
python
|
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
|
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2434-L2485
|
[
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n",
"def _get_first_aggregate_text(node_list):\n '''\n Extract text from the first occurred DOM aggregate.\n '''\n if not node_list:\n return ''\n\n out = []\n for node in node_list[0].childNodes:\n if node.nodeType == dom.Document.TEXT_NODE:\n out.append(node.nodeValue)\n return '\\n'.join(out)\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_get_patches
|
python
|
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
|
List all known patches in repos.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2563-L2576
| null |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
list_patches
|
python
|
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
|
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2579-L2602
|
[
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n",
"def _get_patches(installed_only=False, root=None):\n '''\n List all known patches in repos.\n '''\n patches = {}\n for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):\n installed = element.getAttribute('status') == 'installed'\n if (installed_only and installed) or not installed_only:\n patches[element.getAttribute('name')] = {\n 'installed': installed,\n 'summary': element.getAttribute('summary'),\n }\n\n return patches\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
list_provides
|
python
|
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
|
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2623-L2657
| null |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
resolve_capabilities
|
python
|
def resolve_capabilities(pkgs, refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
'''
if refresh:
refresh_db(root)
ret = list()
for pkg in pkgs:
if isinstance(pkg, dict):
name = next(iter(pkg))
version = pkg[name]
else:
name = pkg
version = None
if kwargs.get('resolve_capabilities', False):
try:
search(name, root=root, match='exact')
except CommandExecutionError:
# no package this such a name found
# search for a package which provides this name
try:
result = search(name, root=root, provides=True, match='exact')
if len(result) == 1:
name = next(iter(result.keys()))
elif len(result) > 1:
log.warning("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})
else:
ret.append(name)
return ret
|
.. versionadded:: 2018.3.0
Convert name provides in ``pkgs`` into real package names if
``resolve_capabilities`` parameter is set to True. In case of
``resolve_capabilities`` is set to False the package list
is returned unchanged.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
resolve_capabilities
If this option is set to True the input will be checked if
a package with this name exists. If not, this function will
search for a package which provides this name. If one is found
the output is exchanged with the real package name.
In case this option is set to False (Default) the input will
be returned unchanged.
CLI Examples:
.. code-block:: bash
salt '*' pkg.resolve_capabilities resolve_capabilities=True w3m_ssl
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L2660-L2723
|
[
"def search(criteria, refresh=False, **kwargs):\n '''\n List known packages, available to the system.\n\n refresh\n force a refresh if set to True.\n If set to False (default) it depends on zypper if a refresh is\n executed.\n\n match (str)\n One of `exact`, `words`, `substrings`. Search for an `exact` match\n or for the whole `words` only. Default to `substrings` to patch\n partial words.\n\n provides (bool)\n Search for packages which provide the search strings.\n\n recommends (bool)\n Search for packages which recommend the search strings.\n\n requires (bool)\n Search for packages which require the search strings.\n\n suggests (bool)\n Search for packages which suggest the search strings.\n\n conflicts (bool)\n Search packages conflicting with search strings.\n\n obsoletes (bool)\n Search for packages which obsolete the search strings.\n\n file_list (bool)\n Search for a match in the file list of packages.\n\n search_descriptions (bool)\n Search also in package summaries and descriptions.\n\n case_sensitive (bool)\n Perform case-sensitive search.\n\n installed_only (bool)\n Show only installed packages.\n\n not_installed_only (bool)\n Show only packages which are not installed.\n\n details (bool)\n Show version and repository\n\n root\n operate on a different root directory.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.search <criteria>\n '''\n ALLOWED_SEARCH_OPTIONS = {\n 'provides': '--provides',\n 'recommends': '--recommends',\n 'requires': '--requires',\n 'suggests': '--suggests',\n 'conflicts': '--conflicts',\n 'obsoletes': '--obsoletes',\n 'file_list': '--file-list',\n 'search_descriptions': '--search-descriptions',\n 'case_sensitive': '--case-sensitive',\n 'installed_only': '--installed-only',\n 'not_installed_only': '-u',\n 'details': '--details'\n }\n\n root = kwargs.get('root', None)\n\n if refresh:\n refresh_db(root)\n\n cmd = ['search']\n if kwargs.get('match') == 'exact':\n cmd.append('--match-exact')\n elif kwargs.get('match') == 'words':\n cmd.append('--match-words')\n elif kwargs.get('match') == 'substrings':\n cmd.append('--match-substrings')\n\n for opt in kwargs:\n if opt in ALLOWED_SEARCH_OPTIONS:\n cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))\n\n cmd.append(criteria)\n solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')\n if not solvables:\n raise CommandExecutionError(\n 'No packages found matching \\'{0}\\''.format(criteria)\n )\n\n out = {}\n for solvable in solvables:\n out[solvable.getAttribute('name')] = dict()\n for k, v in solvable.attributes.items():\n out[solvable.getAttribute('name')][k] = v\n\n return out\n",
"def refresh_db(root=None):\n '''\n Force a repository refresh by calling ``zypper refresh --force``, return a dict::\n\n {'<database name>': Bool}\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n out = __zypper__(root=root).refreshable.call('refresh', '--force')\n\n for line in out.splitlines():\n if not line:\n continue\n if line.strip().startswith('Repository') and '\\'' in line:\n try:\n key = line.split('\\'')[1].strip()\n if 'is up to date' in line:\n ret[key] = False\n except IndexError:\n continue\n elif line.strip().startswith('Building') and '\\'' in line:\n key = line.split('\\'')[1].strip()\n if 'done' in line:\n ret[key] = True\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
import os
import time
import datetime
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
from salt.ext import six
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils.data
import salt.utils.event
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
from salt.utils.versions import LooseVersion
import salt.utils.environment
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.path.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def _clean_cache():
'''
Clean cached results
'''
for cache_name in ['pkg.list_pkgs', 'pkg.list_provides']:
__context__.pop(cache_name, None)
def list_upgrades(refresh=True, root=None, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db(root)
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.functools.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
:param all_versions:
Include information for all versions of the packages installed on the minion.
:param root:
Operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> <package2> <package3> all_versions=True
salt '*' pkg.info_installed <package1> attr=version,vendor all_versions=True
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
all_versions = kwargs.get('all_versions', False)
ret = dict()
for pkg_name, pkgs_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
pkg_nfo = pkgs_nfo if all_versions else [pkgs_nfo]
for _nfo in pkg_nfo:
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in six.iteritems(_nfo):
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
if not all_versions:
ret[pkg_name] = t_nfo
else:
ret.setdefault(pkg_name, []).append(t_nfo)
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
root = kwargs.get('root', None)
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db(root)
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__(root=root).nolock.call('info', '-t', 'package',
*batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower().startswith('yes')
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
else:
ret[name] = ''
# Return a string if only one package name passed
if len(names) == 1 and ret:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, root=None, includes=None, **kwargs):
'''
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
root:
operate on a different root directory.
includes:
List of types of packages to include (package, patch, pattern, product)
By default packages are always included
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
attr = kwargs.get('attr')
if attr is not None:
attr = salt.utils.args.split_input(attr)
includes = includes if includes else []
contextkey = 'pkg.list_pkgs'
# TODO(aplanas): this cached value depends on the parameters
if contextkey not in __context__:
ret = {}
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat',
salt.utils.pkg.rpm.QUERYFORMAT.replace('%{REPOID}', '(none)') + '\n'])
output = __salt__['cmd.run'](cmd,
python_shell=False,
output_loglevel='trace')
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(
line,
osarch=__grains__['osarch']
)
if pkginfo:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = ''
release = ''
if ':' in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if '-' in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
'epoch': epoch,
'version': pkgver,
'release': release,
'arch': pkginfo.arch,
'install_date': pkginfo.install_date,
'install_date_time_t': pkginfo.install_date_time_t
}
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, all_attr)
_ret = {}
for pkgname in ret:
# Filter out GPG public keys packages
if pkgname.startswith('gpg-pubkey'):
continue
_ret[pkgname] = sorted(ret[pkgname], key=lambda d: d['version'])
for include in includes:
if include in ('pattern', 'patch'):
if include == 'pattern':
pkgs = list_installed_patterns(root=root)
elif include == 'patch':
pkgs = list_installed_patches(root=root)
else:
pkgs = []
for pkg in pkgs:
pkg_extended_name = '{}:{}'.format(include, pkg)
info = info_available(pkg_extended_name,
refresh=False,
root=root)
_ret[pkg_extended_name] = [{
'epoch': None,
'version': info[pkg]['version'],
'release': None,
'arch': info[pkg]['arch'],
'install_date': None,
'install_date_time_t': None,
}]
__context__[contextkey] = _ret
return __salt__['pkg_resource.format_pkg_list'](
__context__[contextkey],
versions_as_list,
attr)
def list_repo_pkgs(*args, **kwargs):
'''
.. versionadded:: 2017.7.5,2018.3.1
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.3-83.3.1',
'4.3-82.6'],
'vim': ['7.4.326-12.1']
}
{
'OSS': {
'bash': ['4.3-82.6'],
'vim': ['7.4.326-12.1']
},
'OSS Update': {
'bash': ['4.3-83.3.1']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
salt '*' pkg.list_repo_pkgs 'python2-*' fromrepo='OSS Updates'
'''
byrepo = kwargs.pop('byrepo', False)
fromrepo = kwargs.pop('fromrepo', '') or ''
ret = {}
targets = [
arg if isinstance(arg, six.string_types) else six.text_type(arg)
for arg in args
]
def _is_match(pkgname):
'''
When package names are passed to a zypper search, they will be matched
anywhere in the package name. This makes sure that only exact or
fnmatch matches are identified.
'''
if not args:
# No package names passed, everyone's a winner!
return True
for target in targets:
if fnmatch.fnmatch(pkgname, target):
return True
return False
root = kwargs.get('root') or None
for node in __zypper__(root=root).xml.call('se', '-s', *targets).getElementsByTagName('solvable'):
pkginfo = dict(node.attributes.items())
try:
if pkginfo['kind'] != 'package':
continue
reponame = pkginfo['repository']
if fromrepo and reponame != fromrepo:
continue
pkgname = pkginfo['name']
pkgversion = pkginfo['edition']
except KeyError:
continue
else:
if _is_match(pkgname):
repo_dict = ret.setdefault(reponame, {})
version_list = repo_dict.setdefault(pkgname, set())
version_list.add(pkgversion)
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
[LooseVersion(x) for x in ret[reponame][pkgname]],
reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}
for reponame in ret:
for pkgname in ret[reponame]:
byrepo_ret.setdefault(pkgname, []).extend(ret[reponame][pkgname])
for pkgname in byrepo_ret:
sorted_versions = sorted(
[LooseVersion(x) for x in byrepo_ret[pkgname]],
reverse=True
)
byrepo_ret[pkgname] = [x.vstring for x in sorted_versions]
return byrepo_ret
def _get_configured_repos(root=None):
'''
Get all the info about repositories from the configurations.
'''
repos = os.path.join(root, os.path.relpath(REPOS, os.path.sep)) if root else REPOS
repos_cfg = configparser.ConfigParser()
if os.path.exists(repos):
repos_cfg.read([repos + '/' + fname for fname in os.listdir(repos) if fname.endswith(".repo")])
else:
log.warning('Repositories not found in %s', repos)
return repos_cfg
def _get_repo_info(alias, repos_cfg=None, root=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos(root=root)).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo, root=root)
def list_repos(root=None, **kwargs):
'''
Lists all repos.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos(root=root)
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
return all_repos
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (True or False) repository,
but do not remove if disabled.
refresh
Enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GPG check for this repository.
gpgautoimport : False
If set to True, automatically trust and import public GPG key for
the repository.
root
operate on a different root directory.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
URL can only be deleted if a ``mirrorlist`` is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
root = kwargs.get('root') or None
repos_cfg = _get_configured_repos(root=root)
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg, root=root)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__(root=root).xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos(root=root)
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo, root=root)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo, root=root)
return mod_repo(repo, root=root, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__(root=root).refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__(root=root).xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo, root=root)
if comment:
repo['comment'] = comment
return repo
def refresh_db(root=None):
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2})
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
no_recommends=False,
root=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
resolve_capabilities
If this option is set to True zypper will take capabilities into
account. In this case names which are just provided by a package
will get installed. Default is False.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
no_recommends
Do not install recommended packages, only required ones.
root
operate on a different root directory.
diff_attr:
If a list of package attributes is specified, returned value will
contain them, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
If an attribute list is specified in ``diff_attr``, the dict will also contain
any specified attribute, eg.::
{'<package>': {
'old': {
'version': '<old-version>',
'arch': '<old-arch>'},
'new': {
'version': '<new-version>',
'arch': '<new-arch>'}}}
'''
if refresh:
refresh_db(root)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
version_num = Wildcard(__zypper__(root=root))(name, version)
if version_num:
if pkgs is None and sources is None:
# Allow "version" to work for single package target
pkg_params = {name: version_num}
else:
log.warning('"version" parameter will be ignored for multiple '
'package targets')
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches(root=root)
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append('patch:{}'.format(advisory_id))
else:
targets = pkg_params
diff_attr = kwargs.get("diff_attr")
includes = _find_types(targets)
old = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
cmd_install.append(kwargs.get('resolve_capabilities') and '--capability' or '--name')
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
if no_recommends:
cmd_install.append('--no-recommends')
errors = []
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope, root=root).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure, root=root).call(*cmd)
_clean_cache()
new = list_pkgs(attr=diff_attr, root=root, includes=includes) if not downloadonly else list_downloaded(root)
ret = salt.utils.data.compare_dicts(old, new)
# If something else from packages are included in the search,
# better clean the cache.
if includes:
_clean_cache()
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
no_recommends=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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
no_recommends
Do not install recommended packages, only required ones.
root
Operate on a different root directory.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db(root)
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if no_recommends:
cmd_update.append('--no-recommends')
log.info('Disabling recommendations')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs(root=root)
__zypper__(systemd_scope=_systemd_scope(), root=root).noraise.call(*cmd_update)
_clean_cache()
new = list_pkgs(root=root)
ret = salt.utils.data.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None, root=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
includes = _find_types(pkg_params.keys())
old = list_pkgs(root=root, includes=includes)
targets = []
for target in pkg_params:
# Check if package version set to be removed is actually installed:
# old[target] contains a comma-separated list of installed versions
if target in old and pkg_params[target] in old[target].split(','):
targets.append(target + "-" + pkg_params[target])
elif target in old and not pkg_params[target]:
targets.append(target)
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope, root=root).call('remove', *targets[:500])
targets = targets[500:]
_clean_cache()
new = list_pkgs(root=root, includes=includes)
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
'''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') \
or salt.utils.pkg.rpm.check_32(arch, osarch=__grains__['osarch']):
return name[:-(len(arch) + 1)]
return name
def remove(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def purge(name=None, pkgs=None, 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
root
Operate on a different root directory.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs, root=root)
def list_locks(root=None):
'''
List current package locks.
root
operate on a different root directory.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
_locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
try:
with salt.utils.files.fopen(_locks) as fhr:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
except IOError:
pass
except Exception:
log.warning('Detected a problem when accessing %s', _locks)
return locks
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
locks = os.path.join(root, os.path.relpath(LOCKS, os.path.sep)) if root else LOCKS
if not os.path.exists(locks):
return out
for node in __zypper__(root=root).xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def unhold(name=None, pkgs=None, **kwargs):
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root)
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in pkgs:
if locks.get(pkg):
removed.append(pkg)
ret[pkg]['comment'] = 'Package {0} is no longer held.'.format(pkg)
else:
missing.append(pkg)
ret[pkg]['comment'] = 'Package {0} unable to be unheld.'.format(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return ret
def remove_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use unhold() instead.')
locks = list_locks(root)
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__(root=root).call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def hold(name=None, pkgs=None, **kwargs):
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
:param name:
:param pkgs:
:param kwargs:
:return:
'''
ret = {}
root = kwargs.get('root')
if (not name and not pkgs) or (name and pkgs):
raise CommandExecutionError('Name or packages must be specified.')
elif name:
pkgs = [name]
locks = list_locks(root=root)
added = []
try:
pkgs = list(__salt__['pkg_resource.parse_targets'](pkgs)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in pkgs:
ret[pkg] = {'name': pkg, 'changes': {}, 'result': False, 'comment': ''}
if not locks.get(pkg):
added.append(pkg)
ret[pkg]['comment'] = 'Package {0} is now being held.'.format(pkg)
else:
ret[pkg]['comment'] = 'Package {0} is already set to be held.'.format(pkg)
if added:
__zypper__(root=root).call('al', *added)
return ret
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
salt.utils.versions.warn_until('Sodium', 'This function is deprecated. Please use hold() instead.')
locks = list_locks(root)
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__(root=root).call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument.
The root parameter can also be passed via the keyword argument.
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages, **kwargs)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages, **kwargs)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths, **kwargs):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
The root parameter can also be passed via the keyword argument.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths, **kwargs)
def _get_patterns(installed_only=None, root=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False, root=None):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db(root)
return _get_patterns(root=root)
def list_installed_patterns(root=None):
'''
List installed patterns on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True, root=root)
def search(criteria, refresh=False, **kwargs):
'''
List known packages, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
match (str)
One of `exact`, `words`, `substrings`. Search for an `exact` match
or for the whole `words` only. Default to `substrings` to patch
partial words.
provides (bool)
Search for packages which provide the search strings.
recommends (bool)
Search for packages which recommend the search strings.
requires (bool)
Search for packages which require the search strings.
suggests (bool)
Search for packages which suggest the search strings.
conflicts (bool)
Search packages conflicting with search strings.
obsoletes (bool)
Search for packages which obsolete the search strings.
file_list (bool)
Search for a match in the file list of packages.
search_descriptions (bool)
Search also in package summaries and descriptions.
case_sensitive (bool)
Perform case-sensitive search.
installed_only (bool)
Show only installed packages.
not_installed_only (bool)
Show only packages which are not installed.
details (bool)
Show version and repository
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
ALLOWED_SEARCH_OPTIONS = {
'provides': '--provides',
'recommends': '--recommends',
'requires': '--requires',
'suggests': '--suggests',
'conflicts': '--conflicts',
'obsoletes': '--obsoletes',
'file_list': '--file-list',
'search_descriptions': '--search-descriptions',
'case_sensitive': '--case-sensitive',
'installed_only': '--installed-only',
'not_installed_only': '-u',
'details': '--details'
}
root = kwargs.get('root', None)
if refresh:
refresh_db(root)
cmd = ['search']
if kwargs.get('match') == 'exact':
cmd.append('--match-exact')
elif kwargs.get('match') == 'words':
cmd.append('--match-words')
elif kwargs.get('match') == 'substrings':
cmd.append('--match-substrings')
for opt in kwargs:
if opt in ALLOWED_SEARCH_OPTIONS:
cmd.append(ALLOWED_SEARCH_OPTIONS.get(opt))
cmd.append(criteria)
solvables = __zypper__(root=root).nolock.noraise.xml.call(*cmd).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in solvables:
out[solvable.getAttribute('name')] = dict()
for k, v in solvable.attributes.items():
out[solvable.getAttribute('name')][k] = v
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False, root=None):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db(root)
ret = list()
OEM_PATH = '/var/lib/suseRegister/OEM'
if root:
OEM_PATH = os.path.join(root, os.path.relpath(OEM_PATH, os.path.sep))
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__(root=root).nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
root = kwargs.get('root', None)
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db(root)
pkg_ret = {}
for dld_result in __zypper__(root=root).xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path'], root=root):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded(root=None):
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
root
operate on a different root directory.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
if root:
CACHE_DIR = os.path.join(root, os.path.relpath(CACHE_DIR, os.path.sep))
ret = {}
for root, dirnames, filenames in salt.utils.path.os_walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths, **kwargs):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
The root parameter can also be passed via the keyword argument.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth, **kwargs)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys(), **kwargs)
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False, root=None):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__(root=root).nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False, root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db(root)
return _get_patches(root=root)
def list_installed_patches(root=None, **kwargs):
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True, root=root)
def list_provides(root=None, **kwargs):
'''
.. versionadded:: 2018.3.0
List package provides of installed packages as a dict.
{'<provided_name>': ['<package_name>', '<package_name>', ...]}
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_provides
'''
ret = __context__.get('pkg.list_provides')
if not ret:
cmd = ['rpm']
if root:
cmd.extend(['--root', root])
cmd.extend(['-qa', '--queryformat', '%{PROVIDES}_|-%{NAME}\n'])
ret = dict()
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
provide, realname = line.split('_|-')
if provide == realname:
continue
if provide not in ret:
ret[provide] = list()
ret[provide].append(realname)
__context__['pkg.list_provides'] = ret
return ret
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_Zypper._reset
|
python
|
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
|
Resets values of the call setup.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L112-L134
|
[
"def get_module_environment(env=None, function=None):\n '''\n Get module optional environment.\n\n To setup an environment option for a particular module,\n add either pillar or config at the minion as follows:\n\n system-environment:\n modules:\n pkg:\n _:\n LC_ALL: en_GB.UTF-8\n FOO: bar\n install:\n HELLO: world\n states:\n pkg:\n _:\n LC_ALL: en_US.Latin-1\n NAME: Fred\n\n So this will export the environment to all the modules,\n states, returnes etc. And calling this function with the globals()\n in that context will fetch the environment for further reuse.\n\n Underscore '_' exports environment for all functions within the module.\n If you want to specifially export environment only for one function,\n specify it as in the example above \"install\".\n\n First will be fetched configuration, where virtual name goes first,\n then the physical name of the module overrides the virtual settings.\n Then pillar settings will override the configuration in the same order.\n\n :param env:\n :param function: name of a particular function\n :return: dict\n '''\n result = {}\n if not env:\n env = {}\n for env_src in [env.get('__opts__', {}), env.get('__pillar__', {})]:\n fname = env.get('__file__', '')\n physical_name = os.path.basename(fname).split('.')[0]\n section = os.path.basename(os.path.dirname(fname))\n m_names = [env.get('__virtualname__')]\n if physical_name not in m_names:\n m_names.append(physical_name)\n for m_name in m_names:\n if not m_name:\n continue\n result.update(env_src.get('system-environment', {}).get(\n section, {}).get(m_name, {}).get('_', {}).copy())\n if function is not None:\n result.update(env_src.get('system-environment', {}).get(\n section, {}).get(m_name, {}).get(function, {}).copy())\n\n return result\n"
] |
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_Zypper._is_error
|
python
|
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
|
Is this is an error code?
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L214-L228
| null |
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_Zypper._is_xml_mode
|
python
|
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
|
Is Zypper's output is in XML format?
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L238-L244
| null |
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_Zypper._check_result
|
python
|
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
|
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L246-L281
| null |
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
_Zypper.__call
|
python
|
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh and '--no-refresh' not in args:
self.__cmd.append('--no-refresh')
if self.__root:
self.__cmd.extend(['--root', self.__root])
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug('Calling Zypper: %s', ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.files.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not self.error_msg,
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return (
self._is_xml_mode() and
dom.parseString(salt.utils.stringutils.to_str(self.__call_result['stdout'])) or
self.__call_result['stdout']
)
|
Call Zypper.
:param state:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L283-L356
| null |
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = {
0: 'Successful run of zypper with no special info.',
100: 'Patches are available for installation.',
101: 'Security patches are available for installation.',
102: 'Installation successful, reboot required.',
103: 'Installation succesful, restart of the package manager itself required.',
}
WARNING_EXIT_CODES = {
6: 'No repositories are defined.',
7: 'The ZYPP library is locked.',
106: 'Some repository had to be disabled temporarily because it failed to refresh. '
'You should check your repository configuration (e.g. zypper ref -f).',
107: 'Installation basically succeeded, but some of the packages %post install scripts returned an error. '
'These packages were successfully unpacked to disk and are registered in the rpm database, '
'but due to the failed install script they may not work as expected. The failed scripts output might '
'reveal what actually went wrong. Any scripts output is also logged to /var/log/zypp/history.'
}
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
# ZYPPER_LOCK is not affected by --root
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = salt.utils.environment.get_module_environment(globals())
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
self.__root = None
# Call status
self.__called = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
if 'root' in kwargs:
self.__root = kwargs['root']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
log.warning(msg)
return self.exit_code not in self.SUCCESS_EXIT_CODES and self.exit_code not in self.WARNING_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
Wildcard._get_available_versions
|
python
|
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
|
Get available versions of the package.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L402-L412
| null |
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
Wildcard._get_scope_versions
|
python
|
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
|
Get available difference between next possible matches.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L414-L424
| null |
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
|
saltstack/salt
|
salt/modules/zypperpkg.py
|
Wildcard._set_version
|
python
|
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
|
Stash operator from the version, if any.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zypperpkg.py#L426-L439
| null |
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
|
saltstack/salt
|
salt/utils/vt.py
|
_cleanup
|
python
|
def _cleanup():
'''
Make sure that any terminal processes still running when __del__ was called
to the waited and cleaned up.
'''
for inst in _ACTIVE[:]:
res = inst.isalive()
if res is not True:
try:
_ACTIVE.remove(inst)
except ValueError:
# This can happen if two threads create a new Terminal instance
# It's harmless that it was already removed, so ignore.
pass
|
Make sure that any terminal processes still running when __del__ was called
to the waited and cleaned up.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vt.py#L78-L91
| null |
# -*- coding: utf-8 -*-
'''
:codeauthor: Pedro Algarvio (pedro@algarvio.me)
salt.utils.vt
~~~~~~~~~~~~~
Virtual Terminal
This code has been heavily inspired by Python's subprocess code, the `non
blocking version of it`__, some minor online snippets about TTY handling
with python including `Python's own ``pty`` source code`__ and `Pexpect`__
which has already surpassed some of the pitfalls that some systems would
get us into.
.. __: http://code.activestate.com/recipes/440554/
.. __: https://github.com/python-mirror/python/blob/3.3/Lib/pty.py
.. __: https://github.com/pexpect/pexpect
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import sys
import time
import errno
import signal
import select
import logging
# Import salt libs
from salt.ext import six
mswindows = (sys.platform == "win32")
try:
# pylint: disable=F0401,W0611
from win32file import ReadFile, WriteFile
from win32pipe import PeekNamedPipe
import msvcrt
import win32api
import win32con
import win32process
# pylint: enable=F0401,W0611
except ImportError:
import pty
import fcntl
import struct
import termios
import resource
# Import salt libs
import salt.utils.crypt
import salt.utils.data
import salt.utils.stringutils
from salt.ext.six import string_types
from salt.log.setup import LOG_LEVELS
log = logging.getLogger(__name__)
class TerminalException(Exception):
'''
Terminal specific exception
'''
# ----- Cleanup Running Instances ------------------------------------------->
# This lists holds Terminal instances for which the underlying process had
# not exited at the time its __del__ method got called: those processes are
# wait()ed for synchronously from _cleanup() when a new Terminal object is
# created, to avoid zombie processes.
_ACTIVE = []
# <---- Cleanup Running Instances --------------------------------------------
class Terminal(object):
'''
I'm a virtual terminal
'''
def __init__(self,
args=None,
executable=None,
shell=False,
cwd=None,
env=None,
preexec_fn=None,
# Terminal Size
rows=None,
cols=None,
# Logging options
log_stdin=None,
log_stdin_level='debug',
log_stdout=None,
log_stdout_level='debug',
log_stderr=None,
log_stderr_level='debug',
# sys.stdXYZ streaming options
stream_stdout=None,
stream_stderr=None,
):
# Let's avoid Zombies!!!
_cleanup()
if not args and not executable:
raise TerminalException(
'You need to pass at least one of "args", "executable" '
)
self.args = args
self.executable = executable
self.shell = shell
self.cwd = cwd
self.env = env
self.preexec_fn = preexec_fn
# ----- Set the desired terminal size ------------------------------->
if rows is None and cols is None:
rows, cols = self.__detect_parent_terminal_size()
elif rows is not None and cols is None:
_, cols = self.__detect_parent_terminal_size()
elif rows is None and cols is not None:
rows, _ = self.__detect_parent_terminal_size()
self.rows = rows
self.cols = cols
# <---- Set the desired terminal size --------------------------------
# ----- Internally Set Attributes ----------------------------------->
self.pid = None
self.stdin = None
self.stdout = None
self.stderr = None
self.child_fd = None
self.child_fde = None
self.closed = True
self.flag_eof_stdout = False
self.flag_eof_stderr = False
self.terminated = True
self.exitstatus = None
self.signalstatus = None
# status returned by os.waitpid
self.status = None
self.__irix_hack = 'irix' in sys.platform.lower()
# <---- Internally Set Attributes ------------------------------------
# ----- Direct Streaming Setup -------------------------------------->
if stream_stdout is True:
self.stream_stdout = sys.stdout
elif stream_stdout is False:
self.stream_stdout = None
elif stream_stdout is not None:
if not hasattr(stream_stdout, 'write') or \
not hasattr(stream_stdout, 'flush') or \
not hasattr(stream_stdout, 'close'):
raise TerminalException(
'\'stream_stdout\' needs to have at least 3 methods, '
'\'write()\', \'flush()\' and \'close()\'.'
)
self.stream_stdout = stream_stdout
else:
raise TerminalException(
'Don\'t know how to handle \'{0}\' as the VT\'s '
'\'stream_stdout\' parameter.'.format(stream_stdout)
)
if stream_stderr is True:
self.stream_stderr = sys.stderr
elif stream_stderr is False:
self.stream_stderr = None
elif stream_stderr is not None:
if not hasattr(stream_stderr, 'write') or \
not hasattr(stream_stderr, 'flush') or \
not hasattr(stream_stderr, 'close'):
raise TerminalException(
'\'stream_stderr\' needs to have at least 3 methods, '
'\'write()\', \'flush()\' and \'close()\'.'
)
self.stream_stderr = stream_stderr
else:
raise TerminalException(
'Don\'t know how to handle \'{0}\' as the VT\'s '
'\'stream_stderr\' parameter.'.format(stream_stderr)
)
# <---- Direct Streaming Setup ---------------------------------------
# ----- Spawn our terminal ------------------------------------------>
try:
self._spawn()
except Exception as err: # pylint: disable=W0703
# A lot can go wrong, so that's why we're catching the most general
# exception type
log.warning(
'Failed to spawn the VT: %s', err,
exc_info_on_loglevel=logging.DEBUG
)
raise TerminalException(
'Failed to spawn the VT. Error: {0}'.format(err)
)
log.debug(
'Child Forked! PID: %s STDOUT_FD: %s STDERR_FD: %s',
self.pid, self.child_fd, self.child_fde
)
terminal_command = ' '.join(self.args)
if 'decode("base64")' in terminal_command or 'base64.b64decode(' in terminal_command:
log.debug('VT: Salt-SSH SHIM Terminal Command executed. Logged to TRACE')
log.trace('Terminal Command: %s', terminal_command)
else:
log.debug('Terminal Command: %s', terminal_command)
# <---- Spawn our terminal -------------------------------------------
# ----- Setup Logging ----------------------------------------------->
# Setup logging after spawned in order to have a pid value
self.stdin_logger_level = LOG_LEVELS.get(log_stdin_level, log_stdin_level)
if log_stdin is True:
self.stdin_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDIN'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stdin is not None:
if not isinstance(log_stdin, logging.Logger):
raise RuntimeError(
'\'log_stdin\' needs to subclass `logging.Logger`'
)
self.stdin_logger = log_stdin
else:
self.stdin_logger = None
self.stdout_logger_level = LOG_LEVELS.get(log_stdout_level, log_stdout_level)
if log_stdout is True:
self.stdout_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDOUT'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stdout is not None:
if not isinstance(log_stdout, logging.Logger):
raise RuntimeError(
'\'log_stdout\' needs to subclass `logging.Logger`'
)
self.stdout_logger = log_stdout
else:
self.stdout_logger = None
self.stderr_logger_level = LOG_LEVELS.get(log_stderr_level, log_stderr_level)
if log_stderr is True:
self.stderr_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDERR'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stderr is not None:
if not isinstance(log_stderr, logging.Logger):
raise RuntimeError(
'\'log_stderr\' needs to subclass `logging.Logger`'
)
self.stderr_logger = log_stderr
else:
self.stderr_logger = None
# <---- Setup Logging ------------------------------------------------
# ----- Common Public API ----------------------------------------------->
def send(self, data):
'''
Send data to the terminal. You are responsible to send any required
line feeds.
'''
return self._send(data)
def sendline(self, data, linesep=os.linesep):
'''
Send the provided data to the terminal appending a line feed.
'''
return self.send('{0}{1}'.format(data, linesep))
def recv(self, maxsize=None):
'''
Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process.
'''
if maxsize is None:
maxsize = 1024
elif maxsize < 1:
maxsize = 1
return self._recv(maxsize)
def close(self, terminate=True, kill=False):
'''
Close the communication with the terminal's child.
If ``terminate`` is ``True`` then additionally try to terminate the
terminal, and if ``kill`` is also ``True``, kill the terminal if
terminating it was not enough.
'''
if not self.closed:
if self.child_fd is not None:
os.close(self.child_fd)
self.child_fd = None
if self.child_fde is not None:
os.close(self.child_fde)
self.child_fde = None
time.sleep(0.1)
if terminate:
if not self.terminate(kill):
raise TerminalException('Failed to terminate child process.')
self.closed = True
@property
def has_unread_data(self):
return self.flag_eof_stderr is False or self.flag_eof_stdout is False
# <---- Common Public API ------------------------------------------------
# ----- Common Internal API --------------------------------------------->
def _translate_newlines(self, data):
if data is None or not data:
return
# PTY's always return \r\n as the line feeds
return data.replace('\r\n', os.linesep)
# <---- Common Internal API ----------------------------------------------
# ----- Context Manager Methods ----------------------------------------->
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close(terminate=True, kill=True)
# Wait for the process to terminate, to avoid zombies.
if self.isalive():
self.wait()
# <---- Context Manager Methods ------------------------------------------
# ----- Platform Specific Methods ------------------------------------------->
if mswindows:
# ----- Windows Methods --------------------------------------------->
def _execute(self):
raise NotImplementedError
def _spawn(self):
raise NotImplementedError
def _recv(self, maxsize):
raise NotImplementedError
def _send(self, data):
raise NotImplementedError
def send_signal(self, sig):
'''
Send a signal to the process
'''
# pylint: disable=E1101
if sig == signal.SIGTERM:
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError('Unsupported signal: {0}'.format(sig))
# pylint: enable=E1101
def terminate(self):
'''
Terminates the process
'''
try:
win32api.TerminateProcess(self._handle, 1)
except OSError:
# ERROR_ACCESS_DENIED (winerror 5) is received when the
# process already died.
ecode = win32process.GetExitCodeProcess(self._handle)
if ecode == win32con.STILL_ACTIVE:
raise
self.exitstatus = ecode
kill = terminate
# <---- Windows Methods --------------------------------------------------
else:
# ----- Linux Methods ----------------------------------------------->
# ----- Internal API ------------------------------------------------>
def _spawn(self):
self.pid, self.child_fd, self.child_fde = self.__fork_ptys()
if isinstance(self.args, string_types):
args = [self.args]
elif self.args:
args = list(self.args)
else:
args = []
if self.shell and self.args:
self.args = ['/bin/sh', '-c', ' '.join(args)]
elif self.shell:
self.args = ['/bin/sh']
else:
self.args = args
if self.executable:
self.args[0] = self.executable
if self.executable is None:
self.executable = self.args[0]
if self.pid == 0:
# Child
self.stdin = sys.stdin.fileno()
self.stdout = sys.stdout.fileno()
self.stderr = sys.stderr.fileno()
# Set the terminal size
self.child_fd = self.stdin
if os.isatty(self.child_fd):
# Only try to set the window size if the parent IS a tty
try:
self.setwinsize(self.rows, self.cols)
except IOError as err:
log.warning(
'Failed to set the VT terminal size: %s',
err, exc_info_on_loglevel=logging.DEBUG
)
# Do not allow child to inherit open file descriptors from
# parent
max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)
try:
os.closerange(pty.STDERR_FILENO + 1, max_fd[0])
except OSError:
pass
if self.cwd is not None:
os.chdir(self.cwd)
if self.preexec_fn:
self.preexec_fn()
if self.env is None:
os.execvp(self.executable, self.args)
else:
os.execvpe(self.executable, self.args, self.env)
# Parent
self.closed = False
self.terminated = False
def __fork_ptys(self):
'''
Fork the PTY
The major difference from the python source is that we separate the
stdout from stderr output.
'''
stdout_parent_fd, stdout_child_fd = pty.openpty()
if stdout_parent_fd < 0 or stdout_child_fd < 0:
raise TerminalException('Failed to open a TTY for stdout')
stderr_parent_fd, stderr_child_fd = pty.openpty()
if stderr_parent_fd < 0 or stderr_child_fd < 0:
raise TerminalException('Failed to open a TTY for stderr')
pid = os.fork()
if pid < pty.CHILD:
raise TerminalException('Failed to fork')
elif pid == pty.CHILD:
# Child.
# Close parent FDs
os.close(stdout_parent_fd)
os.close(stderr_parent_fd)
salt.utils.crypt.reinit_crypto()
# ----- Make STDOUT the controlling PTY --------------------->
child_name = os.ttyname(stdout_child_fd)
# Disconnect from controlling tty. Harmless if not already
# connected
try:
tty_fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
if tty_fd >= 0:
os.close(tty_fd)
# which exception, shouldn't we catch explicitly .. ?
except Exception:
# Already disconnected. This happens if running inside cron
pass
# New session!
os.setsid()
# Verify we are disconnected from controlling tty
# by attempting to open it again.
try:
tty_fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
if tty_fd >= 0:
os.close(tty_fd)
raise TerminalException(
'Failed to disconnect from controlling tty. It is '
'still possible to open /dev/tty.'
)
# which exception, shouldn't we catch explicitly .. ?
except Exception:
# Good! We are disconnected from a controlling tty.
pass
# Verify we can open child pty.
tty_fd = os.open(child_name, os.O_RDWR)
if tty_fd < 0:
raise TerminalException(
'Could not open child pty, {0}'.format(child_name)
)
else:
os.close(tty_fd)
# Verify we now have a controlling tty.
if os.name != 'posix':
# Only do this check in not BSD-like operating systems. BSD-like operating systems breaks at this point
tty_fd = os.open('/dev/tty', os.O_WRONLY)
if tty_fd < 0:
raise TerminalException(
'Could not open controlling tty, /dev/tty'
)
else:
os.close(tty_fd)
# <---- Make STDOUT the controlling PTY ----------------------
# ----- Duplicate Descriptors ------------------------------->
os.dup2(stdout_child_fd, pty.STDIN_FILENO)
os.dup2(stdout_child_fd, pty.STDOUT_FILENO)
os.dup2(stderr_child_fd, pty.STDERR_FILENO)
# <---- Duplicate Descriptors --------------------------------
else:
# Parent. Close Child PTY's
salt.utils.crypt.reinit_crypto()
os.close(stdout_child_fd)
os.close(stderr_child_fd)
return pid, stdout_parent_fd, stderr_parent_fd
def _send(self, data):
if self.child_fd is None:
return None
if not select.select([], [self.child_fd], [], 0)[1]:
return 0
try:
if self.stdin_logger:
self.stdin_logger.log(self.stdin_logger_level, data)
if six.PY3:
written = os.write(self.child_fd, data.encode(__salt_system_encoding__))
else:
written = os.write(self.child_fd, data)
except OSError as why:
if why.errno == errno.EPIPE: # broken pipe
os.close(self.child_fd)
self.child_fd = None
return
raise
return written
def _recv(self, maxsize):
rfds = []
if self.child_fd:
rfds.append(self.child_fd)
if self.child_fde:
rfds.append(self.child_fde)
if not self.isalive():
if not rfds:
return None, None
rlist, _, _ = select.select(rfds, [], [], 0)
if not rlist:
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Brain-dead platform.')
return None, None
elif self.__irix_hack:
# Irix takes a long time before it realizes a child was
# terminated.
# FIXME So does this mean Irix systems are forced to always
# have a 2 second delay when calling read_nonblocking?
# That sucks.
rlist, _, _ = select.select(rfds, [], [], 2)
if not rlist:
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Slow platform.')
return None, None
stderr = ''
stdout = ''
# ----- Store FD Flags ------------------------------------------>
if self.child_fd:
fd_flags = fcntl.fcntl(self.child_fd, fcntl.F_GETFL)
if self.child_fde:
fde_flags = fcntl.fcntl(self.child_fde, fcntl.F_GETFL)
# <---- Store FD Flags -------------------------------------------
# ----- Non blocking Reads -------------------------------------->
if self.child_fd:
fcntl.fcntl(self.child_fd,
fcntl.F_SETFL, fd_flags | os.O_NONBLOCK)
if self.child_fde:
fcntl.fcntl(self.child_fde,
fcntl.F_SETFL, fde_flags | os.O_NONBLOCK)
# <---- Non blocking Reads ---------------------------------------
# ----- Check for any incoming data ----------------------------->
rlist, _, _ = select.select(rfds, [], [], 0)
# <---- Check for any incoming data ------------------------------
# ----- Nothing to Process!? ------------------------------------>
if not rlist:
if not self.isalive():
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Very slow platform.')
return None, None
# <---- Nothing to Process!? -------------------------------------
# ----- Process STDERR ------------------------------------------>
if self.child_fde in rlist:
try:
stderr = self._translate_newlines(
salt.utils.stringutils.to_unicode(
os.read(self.child_fde, maxsize)
)
)
if not stderr:
self.flag_eof_stderr = True
stderr = None
else:
if self.stream_stderr:
self.stream_stderr.write(stderr)
self.stream_stderr.flush()
if self.stderr_logger:
stripped = stderr.rstrip()
if stripped.startswith(os.linesep):
stripped = stripped[len(os.linesep):]
if stripped:
self.stderr_logger.log(self.stderr_logger_level, stripped)
except OSError:
os.close(self.child_fde)
self.child_fde = None
self.flag_eof_stderr = True
stderr = None
finally:
if self.child_fde is not None:
fcntl.fcntl(self.child_fde, fcntl.F_SETFL, fde_flags)
# <---- Process STDERR -------------------------------------------
# ----- Process STDOUT ------------------------------------------>
if self.child_fd in rlist:
try:
stdout = self._translate_newlines(
salt.utils.stringutils.to_unicode(
os.read(self.child_fd, maxsize)
)
)
if not stdout:
self.flag_eof_stdout = True
stdout = None
else:
if self.stream_stdout:
self.stream_stdout.write(salt.utils.stringutils.to_str(stdout))
self.stream_stdout.flush()
if self.stdout_logger:
stripped = stdout.rstrip()
if stripped.startswith(os.linesep):
stripped = stripped[len(os.linesep):]
if stripped:
self.stdout_logger.log(self.stdout_logger_level, stripped)
except OSError:
os.close(self.child_fd)
self.child_fd = None
self.flag_eof_stdout = True
stdout = None
finally:
if self.child_fd is not None:
fcntl.fcntl(self.child_fd, fcntl.F_SETFL, fd_flags)
# <---- Process STDOUT -------------------------------------------
return stdout, stderr
def __detect_parent_terminal_size(self):
try:
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
packed = struct.pack(b'HHHH', 0, 0, 0, 0)
ioctl = fcntl.ioctl(sys.stdin.fileno(), TIOCGWINSZ, packed)
return struct.unpack(b'HHHH', ioctl)[0:2]
except IOError:
# Return a default value of 24x80
return 24, 80
# <---- Internal API -------------------------------------------------
# ----- Public API -------------------------------------------------->
def getwinsize(self):
'''
This returns the terminal window size of the child tty. The return
value is a tuple of (rows, cols).
Thank you for the shortcut PEXPECT
'''
if self.child_fd is None:
raise TerminalException(
'Can\'t check the size of the terminal since we\'re not '
'connected to the child process.'
)
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
packed = struct.pack(b'HHHH', 0, 0, 0, 0)
ioctl = fcntl.ioctl(self.child_fd, TIOCGWINSZ, packed)
return struct.unpack(b'HHHH', ioctl)[0:2]
def setwinsize(self, rows, cols):
'''
This sets the terminal window size of the child tty. This will
cause a SIGWINCH signal to be sent to the child. This does not
change the physical window size. It changes the size reported to
TTY-aware applications like vi or curses -- applications that
respond to the SIGWINCH signal.
Thank you for the shortcut PEXPECT
'''
# Check for buggy platforms. Some Python versions on some platforms
# (notably OSF1 Alpha and RedHat 7.1) truncate the value for
# termios.TIOCSWINSZ. It is not clear why this happens.
# These platforms don't seem to handle the signed int very well;
# yet other platforms like OpenBSD have a large negative value for
# TIOCSWINSZ and they don't have a truncate problem.
# Newer versions of Linux have totally different values for
# TIOCSWINSZ.
# Note that this fix is a hack.
TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
if TIOCSWINSZ == 2148037735:
# Same bits, but with sign.
TIOCSWINSZ = -2146929561
# Note, assume ws_xpixel and ws_ypixel are zero.
packed = struct.pack(b'HHHH', rows, cols, 0, 0)
fcntl.ioctl(self.child_fd, TIOCSWINSZ, packed)
def isalive(self,
_waitpid=os.waitpid,
_wnohang=os.WNOHANG,
_wifexited=os.WIFEXITED,
_wexitstatus=os.WEXITSTATUS,
_wifsignaled=os.WIFSIGNALED,
_wifstopped=os.WIFSTOPPED,
_wtermsig=os.WTERMSIG,
_os_error=os.error,
_errno_echild=errno.ECHILD,
_terminal_exception=TerminalException):
'''
This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the
child process appears to be running or False if not. It can take
literally SECONDS for Solaris to return the right status.
'''
if self.terminated:
return False
if self.has_unread_data is False:
# This is for Linux, which requires the blocking form
# of waitpid to get status of a defunct process.
# This is super-lame. The flag_eof_* would have been set
# in recv(), so this should be safe.
waitpid_options = 0
else:
waitpid_options = _wnohang
try:
pid, status = _waitpid(self.pid, waitpid_options)
except _os_error:
err = sys.exc_info()[1]
# No child processes
if err.errno == _errno_echild:
raise _terminal_exception(
'isalive() encountered condition where "terminated" '
'is 0, but there was no child process. Did someone '
'else call waitpid() on our process?'
)
else:
raise err
# I have to do this twice for Solaris.
# I can't even believe that I figured this out...
# If waitpid() returns 0 it means that no child process
# wishes to report, and the value of status is undefined.
if pid == 0:
try:
### os.WNOHANG # Solaris!
pid, status = _waitpid(self.pid, waitpid_options)
except _os_error as exc:
# This should never happen...
if exc.errno == _errno_echild:
raise _terminal_exception(
'isalive() encountered condition that should '
'never happen. There was no child process. Did '
'someone else call waitpid() on our process?'
)
else:
raise
# If pid is still 0 after two calls to waitpid() then the
# process really is alive. This seems to work on all platforms,
# except for Irix which seems to require a blocking call on
# waitpid or select, so I let recv take care of this situation
# (unfortunately, this requires waiting through the timeout).
if pid == 0:
return True
if pid == 0:
return True
if _wifexited(status):
self.status = status
self.exitstatus = _wexitstatus(status)
self.signalstatus = None
self.terminated = True
elif _wifsignaled(status):
self.status = status
self.exitstatus = None
self.signalstatus = _wtermsig(status)
self.terminated = True
elif _wifstopped(status):
raise _terminal_exception(
'isalive() encountered condition where child process is '
'stopped. This is not supported. Is some other process '
'attempting job control with our child pid?'
)
return False
def terminate(self, force=False):
'''
This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated.
'''
if not self.closed:
self.close(terminate=False)
if not self.isalive():
return True
try:
self.send_signal(signal.SIGHUP)
time.sleep(0.1)
if not self.isalive():
return True
self.send_signal(signal.SIGCONT)
time.sleep(0.1)
if not self.isalive():
return True
self.send_signal(signal.SIGINT)
time.sleep(0.1)
if not self.isalive():
return True
if force:
self.send_signal(signal.SIGKILL)
time.sleep(0.1)
if not self.isalive():
return True
else:
return False
return False
except OSError:
# I think there are kernel timing issues that sometimes cause
# this to happen. I think isalive() reports True, but the
# process is dead to the kernel.
# Make one last attempt to see if the kernel is up to date.
time.sleep(0.1)
if not self.isalive():
return True
else:
return False
def wait(self):
'''
This waits until the child exits internally consuming any remaining
output from the child, thus, no blocking forever because the child
has unread data.
'''
if self.isalive():
while self.isalive():
stdout, stderr = self.recv()
if stdout is None:
break
if stderr is None:
break
else:
raise TerminalException('Cannot wait for dead child process.')
return self.exitstatus
def send_signal(self, sig):
'''
Send a signal to the process
'''
os.kill(self.pid, sig)
def kill(self):
'''
Kill the process with SIGKILL
'''
self.send_signal(signal.SIGKILL)
# <---- Public API ---------------------------------------------------
# <---- Linux Methods ----------------------------------------------------
# ----- Cleanup!!! ------------------------------------------------------>
def __del__(self, _maxsize=sys.maxsize, _active=_ACTIVE): # pylint: disable=W0102
# I've disabled W0102 above which is regarding a dangerous default
# value of [] for _ACTIVE, though, this is how Python itself handles
# their subprocess clean up code.
# XXX: Revisit this cleanup code to make it less dangerous.
if self.pid is None:
# We didn't get to successfully create a child process.
return
# In case the child hasn't been waited on, check if it's done.
if self.isalive() and _ACTIVE is not None:
# Child is still running, keep us alive until we can wait on it.
_ACTIVE.append(self)
# <---- Cleanup!!! -------------------------------------------------------
# <---- Platform Specific Methods --------------------------------------------
|
saltstack/salt
|
salt/utils/vt.py
|
Terminal.sendline
|
python
|
def sendline(self, data, linesep=os.linesep):
'''
Send the provided data to the terminal appending a line feed.
'''
return self.send('{0}{1}'.format(data, linesep))
|
Send the provided data to the terminal appending a line feed.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vt.py#L295-L299
|
[
"def send(self, data):\n '''\n Send data to the terminal. You are responsible to send any required\n line feeds.\n '''\n return self._send(data)\n"
] |
class Terminal(object):
'''
I'm a virtual terminal
'''
def __init__(self,
args=None,
executable=None,
shell=False,
cwd=None,
env=None,
preexec_fn=None,
# Terminal Size
rows=None,
cols=None,
# Logging options
log_stdin=None,
log_stdin_level='debug',
log_stdout=None,
log_stdout_level='debug',
log_stderr=None,
log_stderr_level='debug',
# sys.stdXYZ streaming options
stream_stdout=None,
stream_stderr=None,
):
# Let's avoid Zombies!!!
_cleanup()
if not args and not executable:
raise TerminalException(
'You need to pass at least one of "args", "executable" '
)
self.args = args
self.executable = executable
self.shell = shell
self.cwd = cwd
self.env = env
self.preexec_fn = preexec_fn
# ----- Set the desired terminal size ------------------------------->
if rows is None and cols is None:
rows, cols = self.__detect_parent_terminal_size()
elif rows is not None and cols is None:
_, cols = self.__detect_parent_terminal_size()
elif rows is None and cols is not None:
rows, _ = self.__detect_parent_terminal_size()
self.rows = rows
self.cols = cols
# <---- Set the desired terminal size --------------------------------
# ----- Internally Set Attributes ----------------------------------->
self.pid = None
self.stdin = None
self.stdout = None
self.stderr = None
self.child_fd = None
self.child_fde = None
self.closed = True
self.flag_eof_stdout = False
self.flag_eof_stderr = False
self.terminated = True
self.exitstatus = None
self.signalstatus = None
# status returned by os.waitpid
self.status = None
self.__irix_hack = 'irix' in sys.platform.lower()
# <---- Internally Set Attributes ------------------------------------
# ----- Direct Streaming Setup -------------------------------------->
if stream_stdout is True:
self.stream_stdout = sys.stdout
elif stream_stdout is False:
self.stream_stdout = None
elif stream_stdout is not None:
if not hasattr(stream_stdout, 'write') or \
not hasattr(stream_stdout, 'flush') or \
not hasattr(stream_stdout, 'close'):
raise TerminalException(
'\'stream_stdout\' needs to have at least 3 methods, '
'\'write()\', \'flush()\' and \'close()\'.'
)
self.stream_stdout = stream_stdout
else:
raise TerminalException(
'Don\'t know how to handle \'{0}\' as the VT\'s '
'\'stream_stdout\' parameter.'.format(stream_stdout)
)
if stream_stderr is True:
self.stream_stderr = sys.stderr
elif stream_stderr is False:
self.stream_stderr = None
elif stream_stderr is not None:
if not hasattr(stream_stderr, 'write') or \
not hasattr(stream_stderr, 'flush') or \
not hasattr(stream_stderr, 'close'):
raise TerminalException(
'\'stream_stderr\' needs to have at least 3 methods, '
'\'write()\', \'flush()\' and \'close()\'.'
)
self.stream_stderr = stream_stderr
else:
raise TerminalException(
'Don\'t know how to handle \'{0}\' as the VT\'s '
'\'stream_stderr\' parameter.'.format(stream_stderr)
)
# <---- Direct Streaming Setup ---------------------------------------
# ----- Spawn our terminal ------------------------------------------>
try:
self._spawn()
except Exception as err: # pylint: disable=W0703
# A lot can go wrong, so that's why we're catching the most general
# exception type
log.warning(
'Failed to spawn the VT: %s', err,
exc_info_on_loglevel=logging.DEBUG
)
raise TerminalException(
'Failed to spawn the VT. Error: {0}'.format(err)
)
log.debug(
'Child Forked! PID: %s STDOUT_FD: %s STDERR_FD: %s',
self.pid, self.child_fd, self.child_fde
)
terminal_command = ' '.join(self.args)
if 'decode("base64")' in terminal_command or 'base64.b64decode(' in terminal_command:
log.debug('VT: Salt-SSH SHIM Terminal Command executed. Logged to TRACE')
log.trace('Terminal Command: %s', terminal_command)
else:
log.debug('Terminal Command: %s', terminal_command)
# <---- Spawn our terminal -------------------------------------------
# ----- Setup Logging ----------------------------------------------->
# Setup logging after spawned in order to have a pid value
self.stdin_logger_level = LOG_LEVELS.get(log_stdin_level, log_stdin_level)
if log_stdin is True:
self.stdin_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDIN'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stdin is not None:
if not isinstance(log_stdin, logging.Logger):
raise RuntimeError(
'\'log_stdin\' needs to subclass `logging.Logger`'
)
self.stdin_logger = log_stdin
else:
self.stdin_logger = None
self.stdout_logger_level = LOG_LEVELS.get(log_stdout_level, log_stdout_level)
if log_stdout is True:
self.stdout_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDOUT'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stdout is not None:
if not isinstance(log_stdout, logging.Logger):
raise RuntimeError(
'\'log_stdout\' needs to subclass `logging.Logger`'
)
self.stdout_logger = log_stdout
else:
self.stdout_logger = None
self.stderr_logger_level = LOG_LEVELS.get(log_stderr_level, log_stderr_level)
if log_stderr is True:
self.stderr_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDERR'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stderr is not None:
if not isinstance(log_stderr, logging.Logger):
raise RuntimeError(
'\'log_stderr\' needs to subclass `logging.Logger`'
)
self.stderr_logger = log_stderr
else:
self.stderr_logger = None
# <---- Setup Logging ------------------------------------------------
# ----- Common Public API ----------------------------------------------->
def send(self, data):
'''
Send data to the terminal. You are responsible to send any required
line feeds.
'''
return self._send(data)
def recv(self, maxsize=None):
'''
Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process.
'''
if maxsize is None:
maxsize = 1024
elif maxsize < 1:
maxsize = 1
return self._recv(maxsize)
def close(self, terminate=True, kill=False):
'''
Close the communication with the terminal's child.
If ``terminate`` is ``True`` then additionally try to terminate the
terminal, and if ``kill`` is also ``True``, kill the terminal if
terminating it was not enough.
'''
if not self.closed:
if self.child_fd is not None:
os.close(self.child_fd)
self.child_fd = None
if self.child_fde is not None:
os.close(self.child_fde)
self.child_fde = None
time.sleep(0.1)
if terminate:
if not self.terminate(kill):
raise TerminalException('Failed to terminate child process.')
self.closed = True
@property
def has_unread_data(self):
return self.flag_eof_stderr is False or self.flag_eof_stdout is False
# <---- Common Public API ------------------------------------------------
# ----- Common Internal API --------------------------------------------->
def _translate_newlines(self, data):
if data is None or not data:
return
# PTY's always return \r\n as the line feeds
return data.replace('\r\n', os.linesep)
# <---- Common Internal API ----------------------------------------------
# ----- Context Manager Methods ----------------------------------------->
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close(terminate=True, kill=True)
# Wait for the process to terminate, to avoid zombies.
if self.isalive():
self.wait()
# <---- Context Manager Methods ------------------------------------------
# ----- Platform Specific Methods ------------------------------------------->
if mswindows:
# ----- Windows Methods --------------------------------------------->
def _execute(self):
raise NotImplementedError
def _spawn(self):
raise NotImplementedError
def _recv(self, maxsize):
raise NotImplementedError
def _send(self, data):
raise NotImplementedError
def send_signal(self, sig):
'''
Send a signal to the process
'''
# pylint: disable=E1101
if sig == signal.SIGTERM:
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError('Unsupported signal: {0}'.format(sig))
# pylint: enable=E1101
def terminate(self):
'''
Terminates the process
'''
try:
win32api.TerminateProcess(self._handle, 1)
except OSError:
# ERROR_ACCESS_DENIED (winerror 5) is received when the
# process already died.
ecode = win32process.GetExitCodeProcess(self._handle)
if ecode == win32con.STILL_ACTIVE:
raise
self.exitstatus = ecode
kill = terminate
# <---- Windows Methods --------------------------------------------------
else:
# ----- Linux Methods ----------------------------------------------->
# ----- Internal API ------------------------------------------------>
def _spawn(self):
self.pid, self.child_fd, self.child_fde = self.__fork_ptys()
if isinstance(self.args, string_types):
args = [self.args]
elif self.args:
args = list(self.args)
else:
args = []
if self.shell and self.args:
self.args = ['/bin/sh', '-c', ' '.join(args)]
elif self.shell:
self.args = ['/bin/sh']
else:
self.args = args
if self.executable:
self.args[0] = self.executable
if self.executable is None:
self.executable = self.args[0]
if self.pid == 0:
# Child
self.stdin = sys.stdin.fileno()
self.stdout = sys.stdout.fileno()
self.stderr = sys.stderr.fileno()
# Set the terminal size
self.child_fd = self.stdin
if os.isatty(self.child_fd):
# Only try to set the window size if the parent IS a tty
try:
self.setwinsize(self.rows, self.cols)
except IOError as err:
log.warning(
'Failed to set the VT terminal size: %s',
err, exc_info_on_loglevel=logging.DEBUG
)
# Do not allow child to inherit open file descriptors from
# parent
max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)
try:
os.closerange(pty.STDERR_FILENO + 1, max_fd[0])
except OSError:
pass
if self.cwd is not None:
os.chdir(self.cwd)
if self.preexec_fn:
self.preexec_fn()
if self.env is None:
os.execvp(self.executable, self.args)
else:
os.execvpe(self.executable, self.args, self.env)
# Parent
self.closed = False
self.terminated = False
def __fork_ptys(self):
'''
Fork the PTY
The major difference from the python source is that we separate the
stdout from stderr output.
'''
stdout_parent_fd, stdout_child_fd = pty.openpty()
if stdout_parent_fd < 0 or stdout_child_fd < 0:
raise TerminalException('Failed to open a TTY for stdout')
stderr_parent_fd, stderr_child_fd = pty.openpty()
if stderr_parent_fd < 0 or stderr_child_fd < 0:
raise TerminalException('Failed to open a TTY for stderr')
pid = os.fork()
if pid < pty.CHILD:
raise TerminalException('Failed to fork')
elif pid == pty.CHILD:
# Child.
# Close parent FDs
os.close(stdout_parent_fd)
os.close(stderr_parent_fd)
salt.utils.crypt.reinit_crypto()
# ----- Make STDOUT the controlling PTY --------------------->
child_name = os.ttyname(stdout_child_fd)
# Disconnect from controlling tty. Harmless if not already
# connected
try:
tty_fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
if tty_fd >= 0:
os.close(tty_fd)
# which exception, shouldn't we catch explicitly .. ?
except Exception:
# Already disconnected. This happens if running inside cron
pass
# New session!
os.setsid()
# Verify we are disconnected from controlling tty
# by attempting to open it again.
try:
tty_fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
if tty_fd >= 0:
os.close(tty_fd)
raise TerminalException(
'Failed to disconnect from controlling tty. It is '
'still possible to open /dev/tty.'
)
# which exception, shouldn't we catch explicitly .. ?
except Exception:
# Good! We are disconnected from a controlling tty.
pass
# Verify we can open child pty.
tty_fd = os.open(child_name, os.O_RDWR)
if tty_fd < 0:
raise TerminalException(
'Could not open child pty, {0}'.format(child_name)
)
else:
os.close(tty_fd)
# Verify we now have a controlling tty.
if os.name != 'posix':
# Only do this check in not BSD-like operating systems. BSD-like operating systems breaks at this point
tty_fd = os.open('/dev/tty', os.O_WRONLY)
if tty_fd < 0:
raise TerminalException(
'Could not open controlling tty, /dev/tty'
)
else:
os.close(tty_fd)
# <---- Make STDOUT the controlling PTY ----------------------
# ----- Duplicate Descriptors ------------------------------->
os.dup2(stdout_child_fd, pty.STDIN_FILENO)
os.dup2(stdout_child_fd, pty.STDOUT_FILENO)
os.dup2(stderr_child_fd, pty.STDERR_FILENO)
# <---- Duplicate Descriptors --------------------------------
else:
# Parent. Close Child PTY's
salt.utils.crypt.reinit_crypto()
os.close(stdout_child_fd)
os.close(stderr_child_fd)
return pid, stdout_parent_fd, stderr_parent_fd
def _send(self, data):
if self.child_fd is None:
return None
if not select.select([], [self.child_fd], [], 0)[1]:
return 0
try:
if self.stdin_logger:
self.stdin_logger.log(self.stdin_logger_level, data)
if six.PY3:
written = os.write(self.child_fd, data.encode(__salt_system_encoding__))
else:
written = os.write(self.child_fd, data)
except OSError as why:
if why.errno == errno.EPIPE: # broken pipe
os.close(self.child_fd)
self.child_fd = None
return
raise
return written
def _recv(self, maxsize):
rfds = []
if self.child_fd:
rfds.append(self.child_fd)
if self.child_fde:
rfds.append(self.child_fde)
if not self.isalive():
if not rfds:
return None, None
rlist, _, _ = select.select(rfds, [], [], 0)
if not rlist:
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Brain-dead platform.')
return None, None
elif self.__irix_hack:
# Irix takes a long time before it realizes a child was
# terminated.
# FIXME So does this mean Irix systems are forced to always
# have a 2 second delay when calling read_nonblocking?
# That sucks.
rlist, _, _ = select.select(rfds, [], [], 2)
if not rlist:
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Slow platform.')
return None, None
stderr = ''
stdout = ''
# ----- Store FD Flags ------------------------------------------>
if self.child_fd:
fd_flags = fcntl.fcntl(self.child_fd, fcntl.F_GETFL)
if self.child_fde:
fde_flags = fcntl.fcntl(self.child_fde, fcntl.F_GETFL)
# <---- Store FD Flags -------------------------------------------
# ----- Non blocking Reads -------------------------------------->
if self.child_fd:
fcntl.fcntl(self.child_fd,
fcntl.F_SETFL, fd_flags | os.O_NONBLOCK)
if self.child_fde:
fcntl.fcntl(self.child_fde,
fcntl.F_SETFL, fde_flags | os.O_NONBLOCK)
# <---- Non blocking Reads ---------------------------------------
# ----- Check for any incoming data ----------------------------->
rlist, _, _ = select.select(rfds, [], [], 0)
# <---- Check for any incoming data ------------------------------
# ----- Nothing to Process!? ------------------------------------>
if not rlist:
if not self.isalive():
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Very slow platform.')
return None, None
# <---- Nothing to Process!? -------------------------------------
# ----- Process STDERR ------------------------------------------>
if self.child_fde in rlist:
try:
stderr = self._translate_newlines(
salt.utils.stringutils.to_unicode(
os.read(self.child_fde, maxsize)
)
)
if not stderr:
self.flag_eof_stderr = True
stderr = None
else:
if self.stream_stderr:
self.stream_stderr.write(stderr)
self.stream_stderr.flush()
if self.stderr_logger:
stripped = stderr.rstrip()
if stripped.startswith(os.linesep):
stripped = stripped[len(os.linesep):]
if stripped:
self.stderr_logger.log(self.stderr_logger_level, stripped)
except OSError:
os.close(self.child_fde)
self.child_fde = None
self.flag_eof_stderr = True
stderr = None
finally:
if self.child_fde is not None:
fcntl.fcntl(self.child_fde, fcntl.F_SETFL, fde_flags)
# <---- Process STDERR -------------------------------------------
# ----- Process STDOUT ------------------------------------------>
if self.child_fd in rlist:
try:
stdout = self._translate_newlines(
salt.utils.stringutils.to_unicode(
os.read(self.child_fd, maxsize)
)
)
if not stdout:
self.flag_eof_stdout = True
stdout = None
else:
if self.stream_stdout:
self.stream_stdout.write(salt.utils.stringutils.to_str(stdout))
self.stream_stdout.flush()
if self.stdout_logger:
stripped = stdout.rstrip()
if stripped.startswith(os.linesep):
stripped = stripped[len(os.linesep):]
if stripped:
self.stdout_logger.log(self.stdout_logger_level, stripped)
except OSError:
os.close(self.child_fd)
self.child_fd = None
self.flag_eof_stdout = True
stdout = None
finally:
if self.child_fd is not None:
fcntl.fcntl(self.child_fd, fcntl.F_SETFL, fd_flags)
# <---- Process STDOUT -------------------------------------------
return stdout, stderr
def __detect_parent_terminal_size(self):
try:
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
packed = struct.pack(b'HHHH', 0, 0, 0, 0)
ioctl = fcntl.ioctl(sys.stdin.fileno(), TIOCGWINSZ, packed)
return struct.unpack(b'HHHH', ioctl)[0:2]
except IOError:
# Return a default value of 24x80
return 24, 80
# <---- Internal API -------------------------------------------------
# ----- Public API -------------------------------------------------->
def getwinsize(self):
'''
This returns the terminal window size of the child tty. The return
value is a tuple of (rows, cols).
Thank you for the shortcut PEXPECT
'''
if self.child_fd is None:
raise TerminalException(
'Can\'t check the size of the terminal since we\'re not '
'connected to the child process.'
)
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
packed = struct.pack(b'HHHH', 0, 0, 0, 0)
ioctl = fcntl.ioctl(self.child_fd, TIOCGWINSZ, packed)
return struct.unpack(b'HHHH', ioctl)[0:2]
def setwinsize(self, rows, cols):
'''
This sets the terminal window size of the child tty. This will
cause a SIGWINCH signal to be sent to the child. This does not
change the physical window size. It changes the size reported to
TTY-aware applications like vi or curses -- applications that
respond to the SIGWINCH signal.
Thank you for the shortcut PEXPECT
'''
# Check for buggy platforms. Some Python versions on some platforms
# (notably OSF1 Alpha and RedHat 7.1) truncate the value for
# termios.TIOCSWINSZ. It is not clear why this happens.
# These platforms don't seem to handle the signed int very well;
# yet other platforms like OpenBSD have a large negative value for
# TIOCSWINSZ and they don't have a truncate problem.
# Newer versions of Linux have totally different values for
# TIOCSWINSZ.
# Note that this fix is a hack.
TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
if TIOCSWINSZ == 2148037735:
# Same bits, but with sign.
TIOCSWINSZ = -2146929561
# Note, assume ws_xpixel and ws_ypixel are zero.
packed = struct.pack(b'HHHH', rows, cols, 0, 0)
fcntl.ioctl(self.child_fd, TIOCSWINSZ, packed)
def isalive(self,
_waitpid=os.waitpid,
_wnohang=os.WNOHANG,
_wifexited=os.WIFEXITED,
_wexitstatus=os.WEXITSTATUS,
_wifsignaled=os.WIFSIGNALED,
_wifstopped=os.WIFSTOPPED,
_wtermsig=os.WTERMSIG,
_os_error=os.error,
_errno_echild=errno.ECHILD,
_terminal_exception=TerminalException):
'''
This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the
child process appears to be running or False if not. It can take
literally SECONDS for Solaris to return the right status.
'''
if self.terminated:
return False
if self.has_unread_data is False:
# This is for Linux, which requires the blocking form
# of waitpid to get status of a defunct process.
# This is super-lame. The flag_eof_* would have been set
# in recv(), so this should be safe.
waitpid_options = 0
else:
waitpid_options = _wnohang
try:
pid, status = _waitpid(self.pid, waitpid_options)
except _os_error:
err = sys.exc_info()[1]
# No child processes
if err.errno == _errno_echild:
raise _terminal_exception(
'isalive() encountered condition where "terminated" '
'is 0, but there was no child process. Did someone '
'else call waitpid() on our process?'
)
else:
raise err
# I have to do this twice for Solaris.
# I can't even believe that I figured this out...
# If waitpid() returns 0 it means that no child process
# wishes to report, and the value of status is undefined.
if pid == 0:
try:
### os.WNOHANG # Solaris!
pid, status = _waitpid(self.pid, waitpid_options)
except _os_error as exc:
# This should never happen...
if exc.errno == _errno_echild:
raise _terminal_exception(
'isalive() encountered condition that should '
'never happen. There was no child process. Did '
'someone else call waitpid() on our process?'
)
else:
raise
# If pid is still 0 after two calls to waitpid() then the
# process really is alive. This seems to work on all platforms,
# except for Irix which seems to require a blocking call on
# waitpid or select, so I let recv take care of this situation
# (unfortunately, this requires waiting through the timeout).
if pid == 0:
return True
if pid == 0:
return True
if _wifexited(status):
self.status = status
self.exitstatus = _wexitstatus(status)
self.signalstatus = None
self.terminated = True
elif _wifsignaled(status):
self.status = status
self.exitstatus = None
self.signalstatus = _wtermsig(status)
self.terminated = True
elif _wifstopped(status):
raise _terminal_exception(
'isalive() encountered condition where child process is '
'stopped. This is not supported. Is some other process '
'attempting job control with our child pid?'
)
return False
def terminate(self, force=False):
'''
This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated.
'''
if not self.closed:
self.close(terminate=False)
if not self.isalive():
return True
try:
self.send_signal(signal.SIGHUP)
time.sleep(0.1)
if not self.isalive():
return True
self.send_signal(signal.SIGCONT)
time.sleep(0.1)
if not self.isalive():
return True
self.send_signal(signal.SIGINT)
time.sleep(0.1)
if not self.isalive():
return True
if force:
self.send_signal(signal.SIGKILL)
time.sleep(0.1)
if not self.isalive():
return True
else:
return False
return False
except OSError:
# I think there are kernel timing issues that sometimes cause
# this to happen. I think isalive() reports True, but the
# process is dead to the kernel.
# Make one last attempt to see if the kernel is up to date.
time.sleep(0.1)
if not self.isalive():
return True
else:
return False
def wait(self):
'''
This waits until the child exits internally consuming any remaining
output from the child, thus, no blocking forever because the child
has unread data.
'''
if self.isalive():
while self.isalive():
stdout, stderr = self.recv()
if stdout is None:
break
if stderr is None:
break
else:
raise TerminalException('Cannot wait for dead child process.')
return self.exitstatus
def send_signal(self, sig):
'''
Send a signal to the process
'''
os.kill(self.pid, sig)
def kill(self):
'''
Kill the process with SIGKILL
'''
self.send_signal(signal.SIGKILL)
# <---- Public API ---------------------------------------------------
# <---- Linux Methods ----------------------------------------------------
# ----- Cleanup!!! ------------------------------------------------------>
def __del__(self, _maxsize=sys.maxsize, _active=_ACTIVE): # pylint: disable=W0102
# I've disabled W0102 above which is regarding a dangerous default
# value of [] for _ACTIVE, though, this is how Python itself handles
# their subprocess clean up code.
# XXX: Revisit this cleanup code to make it less dangerous.
if self.pid is None:
# We didn't get to successfully create a child process.
return
# In case the child hasn't been waited on, check if it's done.
if self.isalive() and _ACTIVE is not None:
# Child is still running, keep us alive until we can wait on it.
_ACTIVE.append(self)
|
saltstack/salt
|
salt/utils/vt.py
|
Terminal.recv
|
python
|
def recv(self, maxsize=None):
'''
Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process.
'''
if maxsize is None:
maxsize = 1024
elif maxsize < 1:
maxsize = 1
return self._recv(maxsize)
|
Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vt.py#L301-L311
|
[
"def _recv(self, maxsize):\n rfds = []\n if self.child_fd:\n rfds.append(self.child_fd)\n if self.child_fde:\n rfds.append(self.child_fde)\n\n if not self.isalive():\n if not rfds:\n return None, None\n rlist, _, _ = select.select(rfds, [], [], 0)\n if not rlist:\n self.flag_eof_stdout = self.flag_eof_stderr = True\n log.debug('End of file(EOL). Brain-dead platform.')\n return None, None\n elif self.__irix_hack:\n # Irix takes a long time before it realizes a child was\n # terminated.\n # FIXME So does this mean Irix systems are forced to always\n # have a 2 second delay when calling read_nonblocking?\n # That sucks.\n rlist, _, _ = select.select(rfds, [], [], 2)\n if not rlist:\n self.flag_eof_stdout = self.flag_eof_stderr = True\n log.debug('End of file(EOL). Slow platform.')\n return None, None\n\n stderr = ''\n stdout = ''\n\n # ----- Store FD Flags ------------------------------------------>\n if self.child_fd:\n fd_flags = fcntl.fcntl(self.child_fd, fcntl.F_GETFL)\n if self.child_fde:\n fde_flags = fcntl.fcntl(self.child_fde, fcntl.F_GETFL)\n # <---- Store FD Flags -------------------------------------------\n\n # ----- Non blocking Reads -------------------------------------->\n if self.child_fd:\n fcntl.fcntl(self.child_fd,\n fcntl.F_SETFL, fd_flags | os.O_NONBLOCK)\n if self.child_fde:\n fcntl.fcntl(self.child_fde,\n fcntl.F_SETFL, fde_flags | os.O_NONBLOCK)\n # <---- Non blocking Reads ---------------------------------------\n\n # ----- Check for any incoming data ----------------------------->\n rlist, _, _ = select.select(rfds, [], [], 0)\n # <---- Check for any incoming data ------------------------------\n\n # ----- Nothing to Process!? ------------------------------------>\n if not rlist:\n if not self.isalive():\n self.flag_eof_stdout = self.flag_eof_stderr = True\n log.debug('End of file(EOL). Very slow platform.')\n return None, None\n # <---- Nothing to Process!? -------------------------------------\n\n # ----- Process STDERR ------------------------------------------>\n if self.child_fde in rlist:\n try:\n stderr = self._translate_newlines(\n salt.utils.stringutils.to_unicode(\n os.read(self.child_fde, maxsize)\n )\n )\n\n if not stderr:\n self.flag_eof_stderr = True\n stderr = None\n else:\n if self.stream_stderr:\n self.stream_stderr.write(stderr)\n self.stream_stderr.flush()\n\n if self.stderr_logger:\n stripped = stderr.rstrip()\n if stripped.startswith(os.linesep):\n stripped = stripped[len(os.linesep):]\n if stripped:\n self.stderr_logger.log(self.stderr_logger_level, stripped)\n except OSError:\n os.close(self.child_fde)\n self.child_fde = None\n self.flag_eof_stderr = True\n stderr = None\n finally:\n if self.child_fde is not None:\n fcntl.fcntl(self.child_fde, fcntl.F_SETFL, fde_flags)\n # <---- Process STDERR -------------------------------------------\n\n # ----- Process STDOUT ------------------------------------------>\n if self.child_fd in rlist:\n try:\n stdout = self._translate_newlines(\n salt.utils.stringutils.to_unicode(\n os.read(self.child_fd, maxsize)\n )\n )\n\n if not stdout:\n self.flag_eof_stdout = True\n stdout = None\n else:\n if self.stream_stdout:\n self.stream_stdout.write(salt.utils.stringutils.to_str(stdout))\n self.stream_stdout.flush()\n\n if self.stdout_logger:\n stripped = stdout.rstrip()\n if stripped.startswith(os.linesep):\n stripped = stripped[len(os.linesep):]\n if stripped:\n self.stdout_logger.log(self.stdout_logger_level, stripped)\n except OSError:\n os.close(self.child_fd)\n self.child_fd = None\n self.flag_eof_stdout = True\n stdout = None\n finally:\n if self.child_fd is not None:\n fcntl.fcntl(self.child_fd, fcntl.F_SETFL, fd_flags)\n # <---- Process STDOUT -------------------------------------------\n return stdout, stderr\n"
] |
class Terminal(object):
'''
I'm a virtual terminal
'''
def __init__(self,
args=None,
executable=None,
shell=False,
cwd=None,
env=None,
preexec_fn=None,
# Terminal Size
rows=None,
cols=None,
# Logging options
log_stdin=None,
log_stdin_level='debug',
log_stdout=None,
log_stdout_level='debug',
log_stderr=None,
log_stderr_level='debug',
# sys.stdXYZ streaming options
stream_stdout=None,
stream_stderr=None,
):
# Let's avoid Zombies!!!
_cleanup()
if not args and not executable:
raise TerminalException(
'You need to pass at least one of "args", "executable" '
)
self.args = args
self.executable = executable
self.shell = shell
self.cwd = cwd
self.env = env
self.preexec_fn = preexec_fn
# ----- Set the desired terminal size ------------------------------->
if rows is None and cols is None:
rows, cols = self.__detect_parent_terminal_size()
elif rows is not None and cols is None:
_, cols = self.__detect_parent_terminal_size()
elif rows is None and cols is not None:
rows, _ = self.__detect_parent_terminal_size()
self.rows = rows
self.cols = cols
# <---- Set the desired terminal size --------------------------------
# ----- Internally Set Attributes ----------------------------------->
self.pid = None
self.stdin = None
self.stdout = None
self.stderr = None
self.child_fd = None
self.child_fde = None
self.closed = True
self.flag_eof_stdout = False
self.flag_eof_stderr = False
self.terminated = True
self.exitstatus = None
self.signalstatus = None
# status returned by os.waitpid
self.status = None
self.__irix_hack = 'irix' in sys.platform.lower()
# <---- Internally Set Attributes ------------------------------------
# ----- Direct Streaming Setup -------------------------------------->
if stream_stdout is True:
self.stream_stdout = sys.stdout
elif stream_stdout is False:
self.stream_stdout = None
elif stream_stdout is not None:
if not hasattr(stream_stdout, 'write') or \
not hasattr(stream_stdout, 'flush') or \
not hasattr(stream_stdout, 'close'):
raise TerminalException(
'\'stream_stdout\' needs to have at least 3 methods, '
'\'write()\', \'flush()\' and \'close()\'.'
)
self.stream_stdout = stream_stdout
else:
raise TerminalException(
'Don\'t know how to handle \'{0}\' as the VT\'s '
'\'stream_stdout\' parameter.'.format(stream_stdout)
)
if stream_stderr is True:
self.stream_stderr = sys.stderr
elif stream_stderr is False:
self.stream_stderr = None
elif stream_stderr is not None:
if not hasattr(stream_stderr, 'write') or \
not hasattr(stream_stderr, 'flush') or \
not hasattr(stream_stderr, 'close'):
raise TerminalException(
'\'stream_stderr\' needs to have at least 3 methods, '
'\'write()\', \'flush()\' and \'close()\'.'
)
self.stream_stderr = stream_stderr
else:
raise TerminalException(
'Don\'t know how to handle \'{0}\' as the VT\'s '
'\'stream_stderr\' parameter.'.format(stream_stderr)
)
# <---- Direct Streaming Setup ---------------------------------------
# ----- Spawn our terminal ------------------------------------------>
try:
self._spawn()
except Exception as err: # pylint: disable=W0703
# A lot can go wrong, so that's why we're catching the most general
# exception type
log.warning(
'Failed to spawn the VT: %s', err,
exc_info_on_loglevel=logging.DEBUG
)
raise TerminalException(
'Failed to spawn the VT. Error: {0}'.format(err)
)
log.debug(
'Child Forked! PID: %s STDOUT_FD: %s STDERR_FD: %s',
self.pid, self.child_fd, self.child_fde
)
terminal_command = ' '.join(self.args)
if 'decode("base64")' in terminal_command or 'base64.b64decode(' in terminal_command:
log.debug('VT: Salt-SSH SHIM Terminal Command executed. Logged to TRACE')
log.trace('Terminal Command: %s', terminal_command)
else:
log.debug('Terminal Command: %s', terminal_command)
# <---- Spawn our terminal -------------------------------------------
# ----- Setup Logging ----------------------------------------------->
# Setup logging after spawned in order to have a pid value
self.stdin_logger_level = LOG_LEVELS.get(log_stdin_level, log_stdin_level)
if log_stdin is True:
self.stdin_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDIN'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stdin is not None:
if not isinstance(log_stdin, logging.Logger):
raise RuntimeError(
'\'log_stdin\' needs to subclass `logging.Logger`'
)
self.stdin_logger = log_stdin
else:
self.stdin_logger = None
self.stdout_logger_level = LOG_LEVELS.get(log_stdout_level, log_stdout_level)
if log_stdout is True:
self.stdout_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDOUT'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stdout is not None:
if not isinstance(log_stdout, logging.Logger):
raise RuntimeError(
'\'log_stdout\' needs to subclass `logging.Logger`'
)
self.stdout_logger = log_stdout
else:
self.stdout_logger = None
self.stderr_logger_level = LOG_LEVELS.get(log_stderr_level, log_stderr_level)
if log_stderr is True:
self.stderr_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDERR'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stderr is not None:
if not isinstance(log_stderr, logging.Logger):
raise RuntimeError(
'\'log_stderr\' needs to subclass `logging.Logger`'
)
self.stderr_logger = log_stderr
else:
self.stderr_logger = None
# <---- Setup Logging ------------------------------------------------
# ----- Common Public API ----------------------------------------------->
def send(self, data):
'''
Send data to the terminal. You are responsible to send any required
line feeds.
'''
return self._send(data)
def sendline(self, data, linesep=os.linesep):
'''
Send the provided data to the terminal appending a line feed.
'''
return self.send('{0}{1}'.format(data, linesep))
def close(self, terminate=True, kill=False):
'''
Close the communication with the terminal's child.
If ``terminate`` is ``True`` then additionally try to terminate the
terminal, and if ``kill`` is also ``True``, kill the terminal if
terminating it was not enough.
'''
if not self.closed:
if self.child_fd is not None:
os.close(self.child_fd)
self.child_fd = None
if self.child_fde is not None:
os.close(self.child_fde)
self.child_fde = None
time.sleep(0.1)
if terminate:
if not self.terminate(kill):
raise TerminalException('Failed to terminate child process.')
self.closed = True
@property
def has_unread_data(self):
return self.flag_eof_stderr is False or self.flag_eof_stdout is False
# <---- Common Public API ------------------------------------------------
# ----- Common Internal API --------------------------------------------->
def _translate_newlines(self, data):
if data is None or not data:
return
# PTY's always return \r\n as the line feeds
return data.replace('\r\n', os.linesep)
# <---- Common Internal API ----------------------------------------------
# ----- Context Manager Methods ----------------------------------------->
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close(terminate=True, kill=True)
# Wait for the process to terminate, to avoid zombies.
if self.isalive():
self.wait()
# <---- Context Manager Methods ------------------------------------------
# ----- Platform Specific Methods ------------------------------------------->
if mswindows:
# ----- Windows Methods --------------------------------------------->
def _execute(self):
raise NotImplementedError
def _spawn(self):
raise NotImplementedError
def _recv(self, maxsize):
raise NotImplementedError
def _send(self, data):
raise NotImplementedError
def send_signal(self, sig):
'''
Send a signal to the process
'''
# pylint: disable=E1101
if sig == signal.SIGTERM:
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError('Unsupported signal: {0}'.format(sig))
# pylint: enable=E1101
def terminate(self):
'''
Terminates the process
'''
try:
win32api.TerminateProcess(self._handle, 1)
except OSError:
# ERROR_ACCESS_DENIED (winerror 5) is received when the
# process already died.
ecode = win32process.GetExitCodeProcess(self._handle)
if ecode == win32con.STILL_ACTIVE:
raise
self.exitstatus = ecode
kill = terminate
# <---- Windows Methods --------------------------------------------------
else:
# ----- Linux Methods ----------------------------------------------->
# ----- Internal API ------------------------------------------------>
def _spawn(self):
self.pid, self.child_fd, self.child_fde = self.__fork_ptys()
if isinstance(self.args, string_types):
args = [self.args]
elif self.args:
args = list(self.args)
else:
args = []
if self.shell and self.args:
self.args = ['/bin/sh', '-c', ' '.join(args)]
elif self.shell:
self.args = ['/bin/sh']
else:
self.args = args
if self.executable:
self.args[0] = self.executable
if self.executable is None:
self.executable = self.args[0]
if self.pid == 0:
# Child
self.stdin = sys.stdin.fileno()
self.stdout = sys.stdout.fileno()
self.stderr = sys.stderr.fileno()
# Set the terminal size
self.child_fd = self.stdin
if os.isatty(self.child_fd):
# Only try to set the window size if the parent IS a tty
try:
self.setwinsize(self.rows, self.cols)
except IOError as err:
log.warning(
'Failed to set the VT terminal size: %s',
err, exc_info_on_loglevel=logging.DEBUG
)
# Do not allow child to inherit open file descriptors from
# parent
max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)
try:
os.closerange(pty.STDERR_FILENO + 1, max_fd[0])
except OSError:
pass
if self.cwd is not None:
os.chdir(self.cwd)
if self.preexec_fn:
self.preexec_fn()
if self.env is None:
os.execvp(self.executable, self.args)
else:
os.execvpe(self.executable, self.args, self.env)
# Parent
self.closed = False
self.terminated = False
def __fork_ptys(self):
'''
Fork the PTY
The major difference from the python source is that we separate the
stdout from stderr output.
'''
stdout_parent_fd, stdout_child_fd = pty.openpty()
if stdout_parent_fd < 0 or stdout_child_fd < 0:
raise TerminalException('Failed to open a TTY for stdout')
stderr_parent_fd, stderr_child_fd = pty.openpty()
if stderr_parent_fd < 0 or stderr_child_fd < 0:
raise TerminalException('Failed to open a TTY for stderr')
pid = os.fork()
if pid < pty.CHILD:
raise TerminalException('Failed to fork')
elif pid == pty.CHILD:
# Child.
# Close parent FDs
os.close(stdout_parent_fd)
os.close(stderr_parent_fd)
salt.utils.crypt.reinit_crypto()
# ----- Make STDOUT the controlling PTY --------------------->
child_name = os.ttyname(stdout_child_fd)
# Disconnect from controlling tty. Harmless if not already
# connected
try:
tty_fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
if tty_fd >= 0:
os.close(tty_fd)
# which exception, shouldn't we catch explicitly .. ?
except Exception:
# Already disconnected. This happens if running inside cron
pass
# New session!
os.setsid()
# Verify we are disconnected from controlling tty
# by attempting to open it again.
try:
tty_fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
if tty_fd >= 0:
os.close(tty_fd)
raise TerminalException(
'Failed to disconnect from controlling tty. It is '
'still possible to open /dev/tty.'
)
# which exception, shouldn't we catch explicitly .. ?
except Exception:
# Good! We are disconnected from a controlling tty.
pass
# Verify we can open child pty.
tty_fd = os.open(child_name, os.O_RDWR)
if tty_fd < 0:
raise TerminalException(
'Could not open child pty, {0}'.format(child_name)
)
else:
os.close(tty_fd)
# Verify we now have a controlling tty.
if os.name != 'posix':
# Only do this check in not BSD-like operating systems. BSD-like operating systems breaks at this point
tty_fd = os.open('/dev/tty', os.O_WRONLY)
if tty_fd < 0:
raise TerminalException(
'Could not open controlling tty, /dev/tty'
)
else:
os.close(tty_fd)
# <---- Make STDOUT the controlling PTY ----------------------
# ----- Duplicate Descriptors ------------------------------->
os.dup2(stdout_child_fd, pty.STDIN_FILENO)
os.dup2(stdout_child_fd, pty.STDOUT_FILENO)
os.dup2(stderr_child_fd, pty.STDERR_FILENO)
# <---- Duplicate Descriptors --------------------------------
else:
# Parent. Close Child PTY's
salt.utils.crypt.reinit_crypto()
os.close(stdout_child_fd)
os.close(stderr_child_fd)
return pid, stdout_parent_fd, stderr_parent_fd
def _send(self, data):
if self.child_fd is None:
return None
if not select.select([], [self.child_fd], [], 0)[1]:
return 0
try:
if self.stdin_logger:
self.stdin_logger.log(self.stdin_logger_level, data)
if six.PY3:
written = os.write(self.child_fd, data.encode(__salt_system_encoding__))
else:
written = os.write(self.child_fd, data)
except OSError as why:
if why.errno == errno.EPIPE: # broken pipe
os.close(self.child_fd)
self.child_fd = None
return
raise
return written
def _recv(self, maxsize):
rfds = []
if self.child_fd:
rfds.append(self.child_fd)
if self.child_fde:
rfds.append(self.child_fde)
if not self.isalive():
if not rfds:
return None, None
rlist, _, _ = select.select(rfds, [], [], 0)
if not rlist:
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Brain-dead platform.')
return None, None
elif self.__irix_hack:
# Irix takes a long time before it realizes a child was
# terminated.
# FIXME So does this mean Irix systems are forced to always
# have a 2 second delay when calling read_nonblocking?
# That sucks.
rlist, _, _ = select.select(rfds, [], [], 2)
if not rlist:
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Slow platform.')
return None, None
stderr = ''
stdout = ''
# ----- Store FD Flags ------------------------------------------>
if self.child_fd:
fd_flags = fcntl.fcntl(self.child_fd, fcntl.F_GETFL)
if self.child_fde:
fde_flags = fcntl.fcntl(self.child_fde, fcntl.F_GETFL)
# <---- Store FD Flags -------------------------------------------
# ----- Non blocking Reads -------------------------------------->
if self.child_fd:
fcntl.fcntl(self.child_fd,
fcntl.F_SETFL, fd_flags | os.O_NONBLOCK)
if self.child_fde:
fcntl.fcntl(self.child_fde,
fcntl.F_SETFL, fde_flags | os.O_NONBLOCK)
# <---- Non blocking Reads ---------------------------------------
# ----- Check for any incoming data ----------------------------->
rlist, _, _ = select.select(rfds, [], [], 0)
# <---- Check for any incoming data ------------------------------
# ----- Nothing to Process!? ------------------------------------>
if not rlist:
if not self.isalive():
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Very slow platform.')
return None, None
# <---- Nothing to Process!? -------------------------------------
# ----- Process STDERR ------------------------------------------>
if self.child_fde in rlist:
try:
stderr = self._translate_newlines(
salt.utils.stringutils.to_unicode(
os.read(self.child_fde, maxsize)
)
)
if not stderr:
self.flag_eof_stderr = True
stderr = None
else:
if self.stream_stderr:
self.stream_stderr.write(stderr)
self.stream_stderr.flush()
if self.stderr_logger:
stripped = stderr.rstrip()
if stripped.startswith(os.linesep):
stripped = stripped[len(os.linesep):]
if stripped:
self.stderr_logger.log(self.stderr_logger_level, stripped)
except OSError:
os.close(self.child_fde)
self.child_fde = None
self.flag_eof_stderr = True
stderr = None
finally:
if self.child_fde is not None:
fcntl.fcntl(self.child_fde, fcntl.F_SETFL, fde_flags)
# <---- Process STDERR -------------------------------------------
# ----- Process STDOUT ------------------------------------------>
if self.child_fd in rlist:
try:
stdout = self._translate_newlines(
salt.utils.stringutils.to_unicode(
os.read(self.child_fd, maxsize)
)
)
if not stdout:
self.flag_eof_stdout = True
stdout = None
else:
if self.stream_stdout:
self.stream_stdout.write(salt.utils.stringutils.to_str(stdout))
self.stream_stdout.flush()
if self.stdout_logger:
stripped = stdout.rstrip()
if stripped.startswith(os.linesep):
stripped = stripped[len(os.linesep):]
if stripped:
self.stdout_logger.log(self.stdout_logger_level, stripped)
except OSError:
os.close(self.child_fd)
self.child_fd = None
self.flag_eof_stdout = True
stdout = None
finally:
if self.child_fd is not None:
fcntl.fcntl(self.child_fd, fcntl.F_SETFL, fd_flags)
# <---- Process STDOUT -------------------------------------------
return stdout, stderr
def __detect_parent_terminal_size(self):
try:
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
packed = struct.pack(b'HHHH', 0, 0, 0, 0)
ioctl = fcntl.ioctl(sys.stdin.fileno(), TIOCGWINSZ, packed)
return struct.unpack(b'HHHH', ioctl)[0:2]
except IOError:
# Return a default value of 24x80
return 24, 80
# <---- Internal API -------------------------------------------------
# ----- Public API -------------------------------------------------->
def getwinsize(self):
'''
This returns the terminal window size of the child tty. The return
value is a tuple of (rows, cols).
Thank you for the shortcut PEXPECT
'''
if self.child_fd is None:
raise TerminalException(
'Can\'t check the size of the terminal since we\'re not '
'connected to the child process.'
)
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
packed = struct.pack(b'HHHH', 0, 0, 0, 0)
ioctl = fcntl.ioctl(self.child_fd, TIOCGWINSZ, packed)
return struct.unpack(b'HHHH', ioctl)[0:2]
def setwinsize(self, rows, cols):
'''
This sets the terminal window size of the child tty. This will
cause a SIGWINCH signal to be sent to the child. This does not
change the physical window size. It changes the size reported to
TTY-aware applications like vi or curses -- applications that
respond to the SIGWINCH signal.
Thank you for the shortcut PEXPECT
'''
# Check for buggy platforms. Some Python versions on some platforms
# (notably OSF1 Alpha and RedHat 7.1) truncate the value for
# termios.TIOCSWINSZ. It is not clear why this happens.
# These platforms don't seem to handle the signed int very well;
# yet other platforms like OpenBSD have a large negative value for
# TIOCSWINSZ and they don't have a truncate problem.
# Newer versions of Linux have totally different values for
# TIOCSWINSZ.
# Note that this fix is a hack.
TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
if TIOCSWINSZ == 2148037735:
# Same bits, but with sign.
TIOCSWINSZ = -2146929561
# Note, assume ws_xpixel and ws_ypixel are zero.
packed = struct.pack(b'HHHH', rows, cols, 0, 0)
fcntl.ioctl(self.child_fd, TIOCSWINSZ, packed)
def isalive(self,
_waitpid=os.waitpid,
_wnohang=os.WNOHANG,
_wifexited=os.WIFEXITED,
_wexitstatus=os.WEXITSTATUS,
_wifsignaled=os.WIFSIGNALED,
_wifstopped=os.WIFSTOPPED,
_wtermsig=os.WTERMSIG,
_os_error=os.error,
_errno_echild=errno.ECHILD,
_terminal_exception=TerminalException):
'''
This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the
child process appears to be running or False if not. It can take
literally SECONDS for Solaris to return the right status.
'''
if self.terminated:
return False
if self.has_unread_data is False:
# This is for Linux, which requires the blocking form
# of waitpid to get status of a defunct process.
# This is super-lame. The flag_eof_* would have been set
# in recv(), so this should be safe.
waitpid_options = 0
else:
waitpid_options = _wnohang
try:
pid, status = _waitpid(self.pid, waitpid_options)
except _os_error:
err = sys.exc_info()[1]
# No child processes
if err.errno == _errno_echild:
raise _terminal_exception(
'isalive() encountered condition where "terminated" '
'is 0, but there was no child process. Did someone '
'else call waitpid() on our process?'
)
else:
raise err
# I have to do this twice for Solaris.
# I can't even believe that I figured this out...
# If waitpid() returns 0 it means that no child process
# wishes to report, and the value of status is undefined.
if pid == 0:
try:
### os.WNOHANG # Solaris!
pid, status = _waitpid(self.pid, waitpid_options)
except _os_error as exc:
# This should never happen...
if exc.errno == _errno_echild:
raise _terminal_exception(
'isalive() encountered condition that should '
'never happen. There was no child process. Did '
'someone else call waitpid() on our process?'
)
else:
raise
# If pid is still 0 after two calls to waitpid() then the
# process really is alive. This seems to work on all platforms,
# except for Irix which seems to require a blocking call on
# waitpid or select, so I let recv take care of this situation
# (unfortunately, this requires waiting through the timeout).
if pid == 0:
return True
if pid == 0:
return True
if _wifexited(status):
self.status = status
self.exitstatus = _wexitstatus(status)
self.signalstatus = None
self.terminated = True
elif _wifsignaled(status):
self.status = status
self.exitstatus = None
self.signalstatus = _wtermsig(status)
self.terminated = True
elif _wifstopped(status):
raise _terminal_exception(
'isalive() encountered condition where child process is '
'stopped. This is not supported. Is some other process '
'attempting job control with our child pid?'
)
return False
def terminate(self, force=False):
'''
This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated.
'''
if not self.closed:
self.close(terminate=False)
if not self.isalive():
return True
try:
self.send_signal(signal.SIGHUP)
time.sleep(0.1)
if not self.isalive():
return True
self.send_signal(signal.SIGCONT)
time.sleep(0.1)
if not self.isalive():
return True
self.send_signal(signal.SIGINT)
time.sleep(0.1)
if not self.isalive():
return True
if force:
self.send_signal(signal.SIGKILL)
time.sleep(0.1)
if not self.isalive():
return True
else:
return False
return False
except OSError:
# I think there are kernel timing issues that sometimes cause
# this to happen. I think isalive() reports True, but the
# process is dead to the kernel.
# Make one last attempt to see if the kernel is up to date.
time.sleep(0.1)
if not self.isalive():
return True
else:
return False
def wait(self):
'''
This waits until the child exits internally consuming any remaining
output from the child, thus, no blocking forever because the child
has unread data.
'''
if self.isalive():
while self.isalive():
stdout, stderr = self.recv()
if stdout is None:
break
if stderr is None:
break
else:
raise TerminalException('Cannot wait for dead child process.')
return self.exitstatus
def send_signal(self, sig):
'''
Send a signal to the process
'''
os.kill(self.pid, sig)
def kill(self):
'''
Kill the process with SIGKILL
'''
self.send_signal(signal.SIGKILL)
# <---- Public API ---------------------------------------------------
# <---- Linux Methods ----------------------------------------------------
# ----- Cleanup!!! ------------------------------------------------------>
def __del__(self, _maxsize=sys.maxsize, _active=_ACTIVE): # pylint: disable=W0102
# I've disabled W0102 above which is regarding a dangerous default
# value of [] for _ACTIVE, though, this is how Python itself handles
# their subprocess clean up code.
# XXX: Revisit this cleanup code to make it less dangerous.
if self.pid is None:
# We didn't get to successfully create a child process.
return
# In case the child hasn't been waited on, check if it's done.
if self.isalive() and _ACTIVE is not None:
# Child is still running, keep us alive until we can wait on it.
_ACTIVE.append(self)
|
saltstack/salt
|
salt/utils/vt.py
|
Terminal.close
|
python
|
def close(self, terminate=True, kill=False):
'''
Close the communication with the terminal's child.
If ``terminate`` is ``True`` then additionally try to terminate the
terminal, and if ``kill`` is also ``True``, kill the terminal if
terminating it was not enough.
'''
if not self.closed:
if self.child_fd is not None:
os.close(self.child_fd)
self.child_fd = None
if self.child_fde is not None:
os.close(self.child_fde)
self.child_fde = None
time.sleep(0.1)
if terminate:
if not self.terminate(kill):
raise TerminalException('Failed to terminate child process.')
self.closed = True
|
Close the communication with the terminal's child.
If ``terminate`` is ``True`` then additionally try to terminate the
terminal, and if ``kill`` is also ``True``, kill the terminal if
terminating it was not enough.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vt.py#L313-L331
|
[
"def terminate(self, force=False):\n '''\n This forces a child process to terminate. It starts nicely with\n SIGHUP and SIGINT. If \"force\" is True then moves onto SIGKILL. This\n returns True if the child was terminated. This returns False if the\n child could not be terminated.\n '''\n if not self.closed:\n self.close(terminate=False)\n\n if not self.isalive():\n return True\n try:\n self.send_signal(signal.SIGHUP)\n time.sleep(0.1)\n if not self.isalive():\n return True\n self.send_signal(signal.SIGCONT)\n time.sleep(0.1)\n if not self.isalive():\n return True\n self.send_signal(signal.SIGINT)\n time.sleep(0.1)\n if not self.isalive():\n return True\n if force:\n self.send_signal(signal.SIGKILL)\n time.sleep(0.1)\n if not self.isalive():\n return True\n else:\n return False\n return False\n except OSError:\n # I think there are kernel timing issues that sometimes cause\n # this to happen. I think isalive() reports True, but the\n # process is dead to the kernel.\n # Make one last attempt to see if the kernel is up to date.\n time.sleep(0.1)\n if not self.isalive():\n return True\n else:\n return False\n"
] |
class Terminal(object):
'''
I'm a virtual terminal
'''
def __init__(self,
args=None,
executable=None,
shell=False,
cwd=None,
env=None,
preexec_fn=None,
# Terminal Size
rows=None,
cols=None,
# Logging options
log_stdin=None,
log_stdin_level='debug',
log_stdout=None,
log_stdout_level='debug',
log_stderr=None,
log_stderr_level='debug',
# sys.stdXYZ streaming options
stream_stdout=None,
stream_stderr=None,
):
# Let's avoid Zombies!!!
_cleanup()
if not args and not executable:
raise TerminalException(
'You need to pass at least one of "args", "executable" '
)
self.args = args
self.executable = executable
self.shell = shell
self.cwd = cwd
self.env = env
self.preexec_fn = preexec_fn
# ----- Set the desired terminal size ------------------------------->
if rows is None and cols is None:
rows, cols = self.__detect_parent_terminal_size()
elif rows is not None and cols is None:
_, cols = self.__detect_parent_terminal_size()
elif rows is None and cols is not None:
rows, _ = self.__detect_parent_terminal_size()
self.rows = rows
self.cols = cols
# <---- Set the desired terminal size --------------------------------
# ----- Internally Set Attributes ----------------------------------->
self.pid = None
self.stdin = None
self.stdout = None
self.stderr = None
self.child_fd = None
self.child_fde = None
self.closed = True
self.flag_eof_stdout = False
self.flag_eof_stderr = False
self.terminated = True
self.exitstatus = None
self.signalstatus = None
# status returned by os.waitpid
self.status = None
self.__irix_hack = 'irix' in sys.platform.lower()
# <---- Internally Set Attributes ------------------------------------
# ----- Direct Streaming Setup -------------------------------------->
if stream_stdout is True:
self.stream_stdout = sys.stdout
elif stream_stdout is False:
self.stream_stdout = None
elif stream_stdout is not None:
if not hasattr(stream_stdout, 'write') or \
not hasattr(stream_stdout, 'flush') or \
not hasattr(stream_stdout, 'close'):
raise TerminalException(
'\'stream_stdout\' needs to have at least 3 methods, '
'\'write()\', \'flush()\' and \'close()\'.'
)
self.stream_stdout = stream_stdout
else:
raise TerminalException(
'Don\'t know how to handle \'{0}\' as the VT\'s '
'\'stream_stdout\' parameter.'.format(stream_stdout)
)
if stream_stderr is True:
self.stream_stderr = sys.stderr
elif stream_stderr is False:
self.stream_stderr = None
elif stream_stderr is not None:
if not hasattr(stream_stderr, 'write') or \
not hasattr(stream_stderr, 'flush') or \
not hasattr(stream_stderr, 'close'):
raise TerminalException(
'\'stream_stderr\' needs to have at least 3 methods, '
'\'write()\', \'flush()\' and \'close()\'.'
)
self.stream_stderr = stream_stderr
else:
raise TerminalException(
'Don\'t know how to handle \'{0}\' as the VT\'s '
'\'stream_stderr\' parameter.'.format(stream_stderr)
)
# <---- Direct Streaming Setup ---------------------------------------
# ----- Spawn our terminal ------------------------------------------>
try:
self._spawn()
except Exception as err: # pylint: disable=W0703
# A lot can go wrong, so that's why we're catching the most general
# exception type
log.warning(
'Failed to spawn the VT: %s', err,
exc_info_on_loglevel=logging.DEBUG
)
raise TerminalException(
'Failed to spawn the VT. Error: {0}'.format(err)
)
log.debug(
'Child Forked! PID: %s STDOUT_FD: %s STDERR_FD: %s',
self.pid, self.child_fd, self.child_fde
)
terminal_command = ' '.join(self.args)
if 'decode("base64")' in terminal_command or 'base64.b64decode(' in terminal_command:
log.debug('VT: Salt-SSH SHIM Terminal Command executed. Logged to TRACE')
log.trace('Terminal Command: %s', terminal_command)
else:
log.debug('Terminal Command: %s', terminal_command)
# <---- Spawn our terminal -------------------------------------------
# ----- Setup Logging ----------------------------------------------->
# Setup logging after spawned in order to have a pid value
self.stdin_logger_level = LOG_LEVELS.get(log_stdin_level, log_stdin_level)
if log_stdin is True:
self.stdin_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDIN'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stdin is not None:
if not isinstance(log_stdin, logging.Logger):
raise RuntimeError(
'\'log_stdin\' needs to subclass `logging.Logger`'
)
self.stdin_logger = log_stdin
else:
self.stdin_logger = None
self.stdout_logger_level = LOG_LEVELS.get(log_stdout_level, log_stdout_level)
if log_stdout is True:
self.stdout_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDOUT'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stdout is not None:
if not isinstance(log_stdout, logging.Logger):
raise RuntimeError(
'\'log_stdout\' needs to subclass `logging.Logger`'
)
self.stdout_logger = log_stdout
else:
self.stdout_logger = None
self.stderr_logger_level = LOG_LEVELS.get(log_stderr_level, log_stderr_level)
if log_stderr is True:
self.stderr_logger = logging.getLogger(
'{0}.{1}.PID-{2}.STDERR'.format(
__name__, self.__class__.__name__, self.pid
)
)
elif log_stderr is not None:
if not isinstance(log_stderr, logging.Logger):
raise RuntimeError(
'\'log_stderr\' needs to subclass `logging.Logger`'
)
self.stderr_logger = log_stderr
else:
self.stderr_logger = None
# <---- Setup Logging ------------------------------------------------
# ----- Common Public API ----------------------------------------------->
def send(self, data):
'''
Send data to the terminal. You are responsible to send any required
line feeds.
'''
return self._send(data)
def sendline(self, data, linesep=os.linesep):
'''
Send the provided data to the terminal appending a line feed.
'''
return self.send('{0}{1}'.format(data, linesep))
def recv(self, maxsize=None):
'''
Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process.
'''
if maxsize is None:
maxsize = 1024
elif maxsize < 1:
maxsize = 1
return self._recv(maxsize)
@property
def has_unread_data(self):
return self.flag_eof_stderr is False or self.flag_eof_stdout is False
# <---- Common Public API ------------------------------------------------
# ----- Common Internal API --------------------------------------------->
def _translate_newlines(self, data):
if data is None or not data:
return
# PTY's always return \r\n as the line feeds
return data.replace('\r\n', os.linesep)
# <---- Common Internal API ----------------------------------------------
# ----- Context Manager Methods ----------------------------------------->
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close(terminate=True, kill=True)
# Wait for the process to terminate, to avoid zombies.
if self.isalive():
self.wait()
# <---- Context Manager Methods ------------------------------------------
# ----- Platform Specific Methods ------------------------------------------->
if mswindows:
# ----- Windows Methods --------------------------------------------->
def _execute(self):
raise NotImplementedError
def _spawn(self):
raise NotImplementedError
def _recv(self, maxsize):
raise NotImplementedError
def _send(self, data):
raise NotImplementedError
def send_signal(self, sig):
'''
Send a signal to the process
'''
# pylint: disable=E1101
if sig == signal.SIGTERM:
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError('Unsupported signal: {0}'.format(sig))
# pylint: enable=E1101
def terminate(self):
'''
Terminates the process
'''
try:
win32api.TerminateProcess(self._handle, 1)
except OSError:
# ERROR_ACCESS_DENIED (winerror 5) is received when the
# process already died.
ecode = win32process.GetExitCodeProcess(self._handle)
if ecode == win32con.STILL_ACTIVE:
raise
self.exitstatus = ecode
kill = terminate
# <---- Windows Methods --------------------------------------------------
else:
# ----- Linux Methods ----------------------------------------------->
# ----- Internal API ------------------------------------------------>
def _spawn(self):
self.pid, self.child_fd, self.child_fde = self.__fork_ptys()
if isinstance(self.args, string_types):
args = [self.args]
elif self.args:
args = list(self.args)
else:
args = []
if self.shell and self.args:
self.args = ['/bin/sh', '-c', ' '.join(args)]
elif self.shell:
self.args = ['/bin/sh']
else:
self.args = args
if self.executable:
self.args[0] = self.executable
if self.executable is None:
self.executable = self.args[0]
if self.pid == 0:
# Child
self.stdin = sys.stdin.fileno()
self.stdout = sys.stdout.fileno()
self.stderr = sys.stderr.fileno()
# Set the terminal size
self.child_fd = self.stdin
if os.isatty(self.child_fd):
# Only try to set the window size if the parent IS a tty
try:
self.setwinsize(self.rows, self.cols)
except IOError as err:
log.warning(
'Failed to set the VT terminal size: %s',
err, exc_info_on_loglevel=logging.DEBUG
)
# Do not allow child to inherit open file descriptors from
# parent
max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)
try:
os.closerange(pty.STDERR_FILENO + 1, max_fd[0])
except OSError:
pass
if self.cwd is not None:
os.chdir(self.cwd)
if self.preexec_fn:
self.preexec_fn()
if self.env is None:
os.execvp(self.executable, self.args)
else:
os.execvpe(self.executable, self.args, self.env)
# Parent
self.closed = False
self.terminated = False
def __fork_ptys(self):
'''
Fork the PTY
The major difference from the python source is that we separate the
stdout from stderr output.
'''
stdout_parent_fd, stdout_child_fd = pty.openpty()
if stdout_parent_fd < 0 or stdout_child_fd < 0:
raise TerminalException('Failed to open a TTY for stdout')
stderr_parent_fd, stderr_child_fd = pty.openpty()
if stderr_parent_fd < 0 or stderr_child_fd < 0:
raise TerminalException('Failed to open a TTY for stderr')
pid = os.fork()
if pid < pty.CHILD:
raise TerminalException('Failed to fork')
elif pid == pty.CHILD:
# Child.
# Close parent FDs
os.close(stdout_parent_fd)
os.close(stderr_parent_fd)
salt.utils.crypt.reinit_crypto()
# ----- Make STDOUT the controlling PTY --------------------->
child_name = os.ttyname(stdout_child_fd)
# Disconnect from controlling tty. Harmless if not already
# connected
try:
tty_fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
if tty_fd >= 0:
os.close(tty_fd)
# which exception, shouldn't we catch explicitly .. ?
except Exception:
# Already disconnected. This happens if running inside cron
pass
# New session!
os.setsid()
# Verify we are disconnected from controlling tty
# by attempting to open it again.
try:
tty_fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
if tty_fd >= 0:
os.close(tty_fd)
raise TerminalException(
'Failed to disconnect from controlling tty. It is '
'still possible to open /dev/tty.'
)
# which exception, shouldn't we catch explicitly .. ?
except Exception:
# Good! We are disconnected from a controlling tty.
pass
# Verify we can open child pty.
tty_fd = os.open(child_name, os.O_RDWR)
if tty_fd < 0:
raise TerminalException(
'Could not open child pty, {0}'.format(child_name)
)
else:
os.close(tty_fd)
# Verify we now have a controlling tty.
if os.name != 'posix':
# Only do this check in not BSD-like operating systems. BSD-like operating systems breaks at this point
tty_fd = os.open('/dev/tty', os.O_WRONLY)
if tty_fd < 0:
raise TerminalException(
'Could not open controlling tty, /dev/tty'
)
else:
os.close(tty_fd)
# <---- Make STDOUT the controlling PTY ----------------------
# ----- Duplicate Descriptors ------------------------------->
os.dup2(stdout_child_fd, pty.STDIN_FILENO)
os.dup2(stdout_child_fd, pty.STDOUT_FILENO)
os.dup2(stderr_child_fd, pty.STDERR_FILENO)
# <---- Duplicate Descriptors --------------------------------
else:
# Parent. Close Child PTY's
salt.utils.crypt.reinit_crypto()
os.close(stdout_child_fd)
os.close(stderr_child_fd)
return pid, stdout_parent_fd, stderr_parent_fd
def _send(self, data):
if self.child_fd is None:
return None
if not select.select([], [self.child_fd], [], 0)[1]:
return 0
try:
if self.stdin_logger:
self.stdin_logger.log(self.stdin_logger_level, data)
if six.PY3:
written = os.write(self.child_fd, data.encode(__salt_system_encoding__))
else:
written = os.write(self.child_fd, data)
except OSError as why:
if why.errno == errno.EPIPE: # broken pipe
os.close(self.child_fd)
self.child_fd = None
return
raise
return written
def _recv(self, maxsize):
rfds = []
if self.child_fd:
rfds.append(self.child_fd)
if self.child_fde:
rfds.append(self.child_fde)
if not self.isalive():
if not rfds:
return None, None
rlist, _, _ = select.select(rfds, [], [], 0)
if not rlist:
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Brain-dead platform.')
return None, None
elif self.__irix_hack:
# Irix takes a long time before it realizes a child was
# terminated.
# FIXME So does this mean Irix systems are forced to always
# have a 2 second delay when calling read_nonblocking?
# That sucks.
rlist, _, _ = select.select(rfds, [], [], 2)
if not rlist:
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Slow platform.')
return None, None
stderr = ''
stdout = ''
# ----- Store FD Flags ------------------------------------------>
if self.child_fd:
fd_flags = fcntl.fcntl(self.child_fd, fcntl.F_GETFL)
if self.child_fde:
fde_flags = fcntl.fcntl(self.child_fde, fcntl.F_GETFL)
# <---- Store FD Flags -------------------------------------------
# ----- Non blocking Reads -------------------------------------->
if self.child_fd:
fcntl.fcntl(self.child_fd,
fcntl.F_SETFL, fd_flags | os.O_NONBLOCK)
if self.child_fde:
fcntl.fcntl(self.child_fde,
fcntl.F_SETFL, fde_flags | os.O_NONBLOCK)
# <---- Non blocking Reads ---------------------------------------
# ----- Check for any incoming data ----------------------------->
rlist, _, _ = select.select(rfds, [], [], 0)
# <---- Check for any incoming data ------------------------------
# ----- Nothing to Process!? ------------------------------------>
if not rlist:
if not self.isalive():
self.flag_eof_stdout = self.flag_eof_stderr = True
log.debug('End of file(EOL). Very slow platform.')
return None, None
# <---- Nothing to Process!? -------------------------------------
# ----- Process STDERR ------------------------------------------>
if self.child_fde in rlist:
try:
stderr = self._translate_newlines(
salt.utils.stringutils.to_unicode(
os.read(self.child_fde, maxsize)
)
)
if not stderr:
self.flag_eof_stderr = True
stderr = None
else:
if self.stream_stderr:
self.stream_stderr.write(stderr)
self.stream_stderr.flush()
if self.stderr_logger:
stripped = stderr.rstrip()
if stripped.startswith(os.linesep):
stripped = stripped[len(os.linesep):]
if stripped:
self.stderr_logger.log(self.stderr_logger_level, stripped)
except OSError:
os.close(self.child_fde)
self.child_fde = None
self.flag_eof_stderr = True
stderr = None
finally:
if self.child_fde is not None:
fcntl.fcntl(self.child_fde, fcntl.F_SETFL, fde_flags)
# <---- Process STDERR -------------------------------------------
# ----- Process STDOUT ------------------------------------------>
if self.child_fd in rlist:
try:
stdout = self._translate_newlines(
salt.utils.stringutils.to_unicode(
os.read(self.child_fd, maxsize)
)
)
if not stdout:
self.flag_eof_stdout = True
stdout = None
else:
if self.stream_stdout:
self.stream_stdout.write(salt.utils.stringutils.to_str(stdout))
self.stream_stdout.flush()
if self.stdout_logger:
stripped = stdout.rstrip()
if stripped.startswith(os.linesep):
stripped = stripped[len(os.linesep):]
if stripped:
self.stdout_logger.log(self.stdout_logger_level, stripped)
except OSError:
os.close(self.child_fd)
self.child_fd = None
self.flag_eof_stdout = True
stdout = None
finally:
if self.child_fd is not None:
fcntl.fcntl(self.child_fd, fcntl.F_SETFL, fd_flags)
# <---- Process STDOUT -------------------------------------------
return stdout, stderr
def __detect_parent_terminal_size(self):
try:
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
packed = struct.pack(b'HHHH', 0, 0, 0, 0)
ioctl = fcntl.ioctl(sys.stdin.fileno(), TIOCGWINSZ, packed)
return struct.unpack(b'HHHH', ioctl)[0:2]
except IOError:
# Return a default value of 24x80
return 24, 80
# <---- Internal API -------------------------------------------------
# ----- Public API -------------------------------------------------->
def getwinsize(self):
'''
This returns the terminal window size of the child tty. The return
value is a tuple of (rows, cols).
Thank you for the shortcut PEXPECT
'''
if self.child_fd is None:
raise TerminalException(
'Can\'t check the size of the terminal since we\'re not '
'connected to the child process.'
)
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
packed = struct.pack(b'HHHH', 0, 0, 0, 0)
ioctl = fcntl.ioctl(self.child_fd, TIOCGWINSZ, packed)
return struct.unpack(b'HHHH', ioctl)[0:2]
def setwinsize(self, rows, cols):
'''
This sets the terminal window size of the child tty. This will
cause a SIGWINCH signal to be sent to the child. This does not
change the physical window size. It changes the size reported to
TTY-aware applications like vi or curses -- applications that
respond to the SIGWINCH signal.
Thank you for the shortcut PEXPECT
'''
# Check for buggy platforms. Some Python versions on some platforms
# (notably OSF1 Alpha and RedHat 7.1) truncate the value for
# termios.TIOCSWINSZ. It is not clear why this happens.
# These platforms don't seem to handle the signed int very well;
# yet other platforms like OpenBSD have a large negative value for
# TIOCSWINSZ and they don't have a truncate problem.
# Newer versions of Linux have totally different values for
# TIOCSWINSZ.
# Note that this fix is a hack.
TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
if TIOCSWINSZ == 2148037735:
# Same bits, but with sign.
TIOCSWINSZ = -2146929561
# Note, assume ws_xpixel and ws_ypixel are zero.
packed = struct.pack(b'HHHH', rows, cols, 0, 0)
fcntl.ioctl(self.child_fd, TIOCSWINSZ, packed)
def isalive(self,
_waitpid=os.waitpid,
_wnohang=os.WNOHANG,
_wifexited=os.WIFEXITED,
_wexitstatus=os.WEXITSTATUS,
_wifsignaled=os.WIFSIGNALED,
_wifstopped=os.WIFSTOPPED,
_wtermsig=os.WTERMSIG,
_os_error=os.error,
_errno_echild=errno.ECHILD,
_terminal_exception=TerminalException):
'''
This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the
child process appears to be running or False if not. It can take
literally SECONDS for Solaris to return the right status.
'''
if self.terminated:
return False
if self.has_unread_data is False:
# This is for Linux, which requires the blocking form
# of waitpid to get status of a defunct process.
# This is super-lame. The flag_eof_* would have been set
# in recv(), so this should be safe.
waitpid_options = 0
else:
waitpid_options = _wnohang
try:
pid, status = _waitpid(self.pid, waitpid_options)
except _os_error:
err = sys.exc_info()[1]
# No child processes
if err.errno == _errno_echild:
raise _terminal_exception(
'isalive() encountered condition where "terminated" '
'is 0, but there was no child process. Did someone '
'else call waitpid() on our process?'
)
else:
raise err
# I have to do this twice for Solaris.
# I can't even believe that I figured this out...
# If waitpid() returns 0 it means that no child process
# wishes to report, and the value of status is undefined.
if pid == 0:
try:
### os.WNOHANG # Solaris!
pid, status = _waitpid(self.pid, waitpid_options)
except _os_error as exc:
# This should never happen...
if exc.errno == _errno_echild:
raise _terminal_exception(
'isalive() encountered condition that should '
'never happen. There was no child process. Did '
'someone else call waitpid() on our process?'
)
else:
raise
# If pid is still 0 after two calls to waitpid() then the
# process really is alive. This seems to work on all platforms,
# except for Irix which seems to require a blocking call on
# waitpid or select, so I let recv take care of this situation
# (unfortunately, this requires waiting through the timeout).
if pid == 0:
return True
if pid == 0:
return True
if _wifexited(status):
self.status = status
self.exitstatus = _wexitstatus(status)
self.signalstatus = None
self.terminated = True
elif _wifsignaled(status):
self.status = status
self.exitstatus = None
self.signalstatus = _wtermsig(status)
self.terminated = True
elif _wifstopped(status):
raise _terminal_exception(
'isalive() encountered condition where child process is '
'stopped. This is not supported. Is some other process '
'attempting job control with our child pid?'
)
return False
def terminate(self, force=False):
'''
This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated.
'''
if not self.closed:
self.close(terminate=False)
if not self.isalive():
return True
try:
self.send_signal(signal.SIGHUP)
time.sleep(0.1)
if not self.isalive():
return True
self.send_signal(signal.SIGCONT)
time.sleep(0.1)
if not self.isalive():
return True
self.send_signal(signal.SIGINT)
time.sleep(0.1)
if not self.isalive():
return True
if force:
self.send_signal(signal.SIGKILL)
time.sleep(0.1)
if not self.isalive():
return True
else:
return False
return False
except OSError:
# I think there are kernel timing issues that sometimes cause
# this to happen. I think isalive() reports True, but the
# process is dead to the kernel.
# Make one last attempt to see if the kernel is up to date.
time.sleep(0.1)
if not self.isalive():
return True
else:
return False
def wait(self):
'''
This waits until the child exits internally consuming any remaining
output from the child, thus, no blocking forever because the child
has unread data.
'''
if self.isalive():
while self.isalive():
stdout, stderr = self.recv()
if stdout is None:
break
if stderr is None:
break
else:
raise TerminalException('Cannot wait for dead child process.')
return self.exitstatus
def send_signal(self, sig):
'''
Send a signal to the process
'''
os.kill(self.pid, sig)
def kill(self):
'''
Kill the process with SIGKILL
'''
self.send_signal(signal.SIGKILL)
# <---- Public API ---------------------------------------------------
# <---- Linux Methods ----------------------------------------------------
# ----- Cleanup!!! ------------------------------------------------------>
def __del__(self, _maxsize=sys.maxsize, _active=_ACTIVE): # pylint: disable=W0102
# I've disabled W0102 above which is regarding a dangerous default
# value of [] for _ACTIVE, though, this is how Python itself handles
# their subprocess clean up code.
# XXX: Revisit this cleanup code to make it less dangerous.
if self.pid is None:
# We didn't get to successfully create a child process.
return
# In case the child hasn't been waited on, check if it's done.
if self.isalive() and _ACTIVE is not None:
# Child is still running, keep us alive until we can wait on it.
_ACTIVE.append(self)
|
saltstack/salt
|
salt/states/pyrax_queues.py
|
present
|
python
|
def present(name, provider):
'''
Ensure the RackSpace queue exists.
name
Name of the Rackspace queue.
provider
Salt Cloud Provider
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_present = list(__salt__['cloud.action']('queues_exists', provider=provider, name=name)[provider].values())[0]
if not is_present:
if __opts__['test']:
msg = 'Rackspace queue {0} is set to be created.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
created = __salt__['cloud.action']('queues_create', provider=provider, name=name)
if created:
queue = __salt__['cloud.action']('queues_show', provider=provider, name=name)
ret['changes']['old'] = {}
ret['changes']['new'] = {'queue': queue}
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} Rackspace queue.'.format(name)
return ret
else:
ret['comment'] = '{0} present.'.format(name)
return ret
|
Ensure the RackSpace queue exists.
name
Name of the Rackspace queue.
provider
Salt Cloud Provider
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pyrax_queues.py#L36-L68
| null |
# -*- coding: utf-8 -*-
'''
Manage Rackspace Queues
=======================
.. versionadded:: 2015.5.0
Create and destroy Rackspace queues. Be aware that this interacts with
Rackspace's services, and so may incur charges.
This module uses ``pyrax``, which can be installed via package, or pip.
This module is greatly inspired by boto_* modules from SaltStack code source.
.. code-block:: yaml
myqueue:
pyrax_queues.present:
- provider: my-pyrax
myqueue:
pyrax_queues.absent:
- provider: my-pyrax
'''
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.openstack.pyrax as suop
def __virtual__():
'''
Only load if pyrax is available.
'''
return suop.HAS_PYRAX
def absent(name, provider):
'''
Ensure the named Rackspace queue is deleted.
name
Name of the Rackspace queue.
provider
Salt Cloud provider
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_present = list(__salt__['cloud.action']('queues_exists', provider=provider, name=name)[provider].values())[0]
if is_present:
if __opts__['test']:
ret['comment'] = 'Rackspace queue {0} is set to be removed.'.format(
name)
ret['result'] = None
return ret
queue = __salt__['cloud.action']('queues_show', provider=provider, name=name)
deleted = __salt__['cloud.action']('queues_delete', provider=provider, name=name)
if deleted:
ret['changes']['old'] = queue
ret['changes']['new'] = {}
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} Rackspace queue.'.format(name)
else:
ret['comment'] = '{0} does not exist.'.format(name)
return ret
|
saltstack/salt
|
salt/states/pyrax_queues.py
|
absent
|
python
|
def absent(name, provider):
'''
Ensure the named Rackspace queue is deleted.
name
Name of the Rackspace queue.
provider
Salt Cloud provider
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_present = list(__salt__['cloud.action']('queues_exists', provider=provider, name=name)[provider].values())[0]
if is_present:
if __opts__['test']:
ret['comment'] = 'Rackspace queue {0} is set to be removed.'.format(
name)
ret['result'] = None
return ret
queue = __salt__['cloud.action']('queues_show', provider=provider, name=name)
deleted = __salt__['cloud.action']('queues_delete', provider=provider, name=name)
if deleted:
ret['changes']['old'] = queue
ret['changes']['new'] = {}
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} Rackspace queue.'.format(name)
else:
ret['comment'] = '{0} does not exist.'.format(name)
return ret
|
Ensure the named Rackspace queue is deleted.
name
Name of the Rackspace queue.
provider
Salt Cloud provider
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pyrax_queues.py#L71-L102
| null |
# -*- coding: utf-8 -*-
'''
Manage Rackspace Queues
=======================
.. versionadded:: 2015.5.0
Create and destroy Rackspace queues. Be aware that this interacts with
Rackspace's services, and so may incur charges.
This module uses ``pyrax``, which can be installed via package, or pip.
This module is greatly inspired by boto_* modules from SaltStack code source.
.. code-block:: yaml
myqueue:
pyrax_queues.present:
- provider: my-pyrax
myqueue:
pyrax_queues.absent:
- provider: my-pyrax
'''
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.openstack.pyrax as suop
def __virtual__():
'''
Only load if pyrax is available.
'''
return suop.HAS_PYRAX
def present(name, provider):
'''
Ensure the RackSpace queue exists.
name
Name of the Rackspace queue.
provider
Salt Cloud Provider
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_present = list(__salt__['cloud.action']('queues_exists', provider=provider, name=name)[provider].values())[0]
if not is_present:
if __opts__['test']:
msg = 'Rackspace queue {0} is set to be created.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
created = __salt__['cloud.action']('queues_create', provider=provider, name=name)
if created:
queue = __salt__['cloud.action']('queues_show', provider=provider, name=name)
ret['changes']['old'] = {}
ret['changes']['new'] = {'queue': queue}
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} Rackspace queue.'.format(name)
return ret
else:
ret['comment'] = '{0} present.'.format(name)
return ret
|
saltstack/salt
|
salt/runners/drac.py
|
__connect
|
python
|
def __connect(hostname, timeout=20, username=None, password=None):
'''
Connect to the DRAC
'''
drac_cred = __opts__.get('drac')
err_msg = 'No drac login credentials found. Please add the \'username\' and \'password\' ' \
'fields beneath a \'drac\' key in the master configuration file. Or you can ' \
'pass in a username and password as kwargs at the CLI.'
if not username:
if drac_cred is None:
log.error(err_msg)
return False
username = drac_cred.get('username', None)
if not password:
if drac_cred is None:
log.error(err_msg)
return False
password = drac_cred.get('password', None)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, username=username, password=password, timeout=timeout)
except Exception as e:
log.error('Unable to connect to %s: %s', hostname, e)
return False
return client
|
Connect to the DRAC
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/drac.py#L37-L66
| null |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC from the Master
The login credentials need to be configured in the Salt master
configuration file.
.. code-block: yaml
drac:
username: admin
password: secret
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import 3rd-party libs
try:
import paramiko
HAS_PARAMIKO = True
except ImportError:
HAS_PARAMIKO = False
log = logging.getLogger(__name__)
def __virtual__():
if HAS_PARAMIKO:
return True
return False, 'The drac runner module cannot be loaded: paramiko package is not installed.'
def __version(client):
'''
Grab DRAC version
'''
versions = {9: 'CMC',
8: 'iDRAC6',
10: 'iDRAC6',
11: 'iDRAC6',
16: 'iDRAC7',
17: 'iDRAC7'}
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm getconfig -g idRacInfo')
for i in stdout.readlines():
if i[2:].startswith('idRacType'):
return versions.get(int(i[2:].split('=')[1]), None)
return None
def pxe(hostname, timeout=20, username=None, password=None):
'''
Connect to the Dell DRAC and have the boot order set to PXE
and power cycle the system to PXE boot
CLI Example:
.. code-block:: bash
salt-run drac.pxe example.com
'''
_cmds = [
'racadm config -g cfgServerInfo -o cfgServerFirstBootDevice pxe',
'racadm config -g cfgServerInfo -o cfgServerBootOnce 1',
'racadm serveraction powercycle',
]
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
for i, cmd in enumerate(_cmds, 1):
log.info('Executing command %s', i)
(stdin, stdout, stderr) = client.exec_command(cmd)
if 'successful' in stdout.readline():
log.info('Executing command: %s', cmd)
else:
log.error('Unable to execute: %s', cmd)
return False
return True
def reboot(hostname, timeout=20, username=None, password=None):
'''
Reboot a server using the Dell DRAC
CLI Example:
.. code-block:: bash
salt-run drac.reboot example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powercycle')
if 'successful' in stdout.readline():
log.info('powercycle successful')
else:
log.error('powercycle racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def poweroff(hostname, timeout=20, username=None, password=None):
'''
Power server off
CLI Example:
.. code-block:: bash
salt-run drac.poweroff example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerdown')
if 'successful' in stdout.readline():
log.info('powerdown successful')
else:
log.error('powerdown racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def poweron(hostname, timeout=20, username=None, password=None):
'''
Power server on
CLI Example:
.. code-block:: bash
salt-run drac.poweron example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerup')
if 'successful' in stdout.readline():
log.info('powerup successful')
else:
log.error('powerup racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def version(hostname, timeout=20, username=None, password=None):
'''
Display the version of DRAC
CLI Example:
.. code-block:: bash
salt-run drac.version example.com
'''
return __version(__connect(hostname, timeout, username, password))
|
saltstack/salt
|
salt/runners/drac.py
|
__version
|
python
|
def __version(client):
'''
Grab DRAC version
'''
versions = {9: 'CMC',
8: 'iDRAC6',
10: 'iDRAC6',
11: 'iDRAC6',
16: 'iDRAC7',
17: 'iDRAC7'}
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm getconfig -g idRacInfo')
for i in stdout.readlines():
if i[2:].startswith('idRacType'):
return versions.get(int(i[2:].split('=')[1]), None)
return None
|
Grab DRAC version
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/drac.py#L69-L87
| null |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC from the Master
The login credentials need to be configured in the Salt master
configuration file.
.. code-block: yaml
drac:
username: admin
password: secret
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import 3rd-party libs
try:
import paramiko
HAS_PARAMIKO = True
except ImportError:
HAS_PARAMIKO = False
log = logging.getLogger(__name__)
def __virtual__():
if HAS_PARAMIKO:
return True
return False, 'The drac runner module cannot be loaded: paramiko package is not installed.'
def __connect(hostname, timeout=20, username=None, password=None):
'''
Connect to the DRAC
'''
drac_cred = __opts__.get('drac')
err_msg = 'No drac login credentials found. Please add the \'username\' and \'password\' ' \
'fields beneath a \'drac\' key in the master configuration file. Or you can ' \
'pass in a username and password as kwargs at the CLI.'
if not username:
if drac_cred is None:
log.error(err_msg)
return False
username = drac_cred.get('username', None)
if not password:
if drac_cred is None:
log.error(err_msg)
return False
password = drac_cred.get('password', None)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, username=username, password=password, timeout=timeout)
except Exception as e:
log.error('Unable to connect to %s: %s', hostname, e)
return False
return client
def pxe(hostname, timeout=20, username=None, password=None):
'''
Connect to the Dell DRAC and have the boot order set to PXE
and power cycle the system to PXE boot
CLI Example:
.. code-block:: bash
salt-run drac.pxe example.com
'''
_cmds = [
'racadm config -g cfgServerInfo -o cfgServerFirstBootDevice pxe',
'racadm config -g cfgServerInfo -o cfgServerBootOnce 1',
'racadm serveraction powercycle',
]
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
for i, cmd in enumerate(_cmds, 1):
log.info('Executing command %s', i)
(stdin, stdout, stderr) = client.exec_command(cmd)
if 'successful' in stdout.readline():
log.info('Executing command: %s', cmd)
else:
log.error('Unable to execute: %s', cmd)
return False
return True
def reboot(hostname, timeout=20, username=None, password=None):
'''
Reboot a server using the Dell DRAC
CLI Example:
.. code-block:: bash
salt-run drac.reboot example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powercycle')
if 'successful' in stdout.readline():
log.info('powercycle successful')
else:
log.error('powercycle racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def poweroff(hostname, timeout=20, username=None, password=None):
'''
Power server off
CLI Example:
.. code-block:: bash
salt-run drac.poweroff example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerdown')
if 'successful' in stdout.readline():
log.info('powerdown successful')
else:
log.error('powerdown racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def poweron(hostname, timeout=20, username=None, password=None):
'''
Power server on
CLI Example:
.. code-block:: bash
salt-run drac.poweron example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerup')
if 'successful' in stdout.readline():
log.info('powerup successful')
else:
log.error('powerup racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def version(hostname, timeout=20, username=None, password=None):
'''
Display the version of DRAC
CLI Example:
.. code-block:: bash
salt-run drac.version example.com
'''
return __version(__connect(hostname, timeout, username, password))
|
saltstack/salt
|
salt/runners/drac.py
|
pxe
|
python
|
def pxe(hostname, timeout=20, username=None, password=None):
'''
Connect to the Dell DRAC and have the boot order set to PXE
and power cycle the system to PXE boot
CLI Example:
.. code-block:: bash
salt-run drac.pxe example.com
'''
_cmds = [
'racadm config -g cfgServerInfo -o cfgServerFirstBootDevice pxe',
'racadm config -g cfgServerInfo -o cfgServerBootOnce 1',
'racadm serveraction powercycle',
]
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
for i, cmd in enumerate(_cmds, 1):
log.info('Executing command %s', i)
(stdin, stdout, stderr) = client.exec_command(cmd)
if 'successful' in stdout.readline():
log.info('Executing command: %s', cmd)
else:
log.error('Unable to execute: %s', cmd)
return False
return True
|
Connect to the Dell DRAC and have the boot order set to PXE
and power cycle the system to PXE boot
CLI Example:
.. code-block:: bash
salt-run drac.pxe example.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/drac.py#L90-L121
|
[
"def __connect(hostname, timeout=20, username=None, password=None):\n '''\n Connect to the DRAC\n '''\n drac_cred = __opts__.get('drac')\n err_msg = 'No drac login credentials found. Please add the \\'username\\' and \\'password\\' ' \\\n 'fields beneath a \\'drac\\' key in the master configuration file. Or you can ' \\\n 'pass in a username and password as kwargs at the CLI.'\n\n if not username:\n if drac_cred is None:\n log.error(err_msg)\n return False\n username = drac_cred.get('username', None)\n if not password:\n if drac_cred is None:\n log.error(err_msg)\n return False\n password = drac_cred.get('password', None)\n\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n try:\n client.connect(hostname, username=username, password=password, timeout=timeout)\n except Exception as e:\n log.error('Unable to connect to %s: %s', hostname, e)\n return False\n\n return client\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC from the Master
The login credentials need to be configured in the Salt master
configuration file.
.. code-block: yaml
drac:
username: admin
password: secret
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import 3rd-party libs
try:
import paramiko
HAS_PARAMIKO = True
except ImportError:
HAS_PARAMIKO = False
log = logging.getLogger(__name__)
def __virtual__():
if HAS_PARAMIKO:
return True
return False, 'The drac runner module cannot be loaded: paramiko package is not installed.'
def __connect(hostname, timeout=20, username=None, password=None):
'''
Connect to the DRAC
'''
drac_cred = __opts__.get('drac')
err_msg = 'No drac login credentials found. Please add the \'username\' and \'password\' ' \
'fields beneath a \'drac\' key in the master configuration file. Or you can ' \
'pass in a username and password as kwargs at the CLI.'
if not username:
if drac_cred is None:
log.error(err_msg)
return False
username = drac_cred.get('username', None)
if not password:
if drac_cred is None:
log.error(err_msg)
return False
password = drac_cred.get('password', None)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, username=username, password=password, timeout=timeout)
except Exception as e:
log.error('Unable to connect to %s: %s', hostname, e)
return False
return client
def __version(client):
'''
Grab DRAC version
'''
versions = {9: 'CMC',
8: 'iDRAC6',
10: 'iDRAC6',
11: 'iDRAC6',
16: 'iDRAC7',
17: 'iDRAC7'}
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm getconfig -g idRacInfo')
for i in stdout.readlines():
if i[2:].startswith('idRacType'):
return versions.get(int(i[2:].split('=')[1]), None)
return None
def reboot(hostname, timeout=20, username=None, password=None):
'''
Reboot a server using the Dell DRAC
CLI Example:
.. code-block:: bash
salt-run drac.reboot example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powercycle')
if 'successful' in stdout.readline():
log.info('powercycle successful')
else:
log.error('powercycle racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def poweroff(hostname, timeout=20, username=None, password=None):
'''
Power server off
CLI Example:
.. code-block:: bash
salt-run drac.poweroff example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerdown')
if 'successful' in stdout.readline():
log.info('powerdown successful')
else:
log.error('powerdown racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def poweron(hostname, timeout=20, username=None, password=None):
'''
Power server on
CLI Example:
.. code-block:: bash
salt-run drac.poweron example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerup')
if 'successful' in stdout.readline():
log.info('powerup successful')
else:
log.error('powerup racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def version(hostname, timeout=20, username=None, password=None):
'''
Display the version of DRAC
CLI Example:
.. code-block:: bash
salt-run drac.version example.com
'''
return __version(__connect(hostname, timeout, username, password))
|
saltstack/salt
|
salt/runners/drac.py
|
reboot
|
python
|
def reboot(hostname, timeout=20, username=None, password=None):
'''
Reboot a server using the Dell DRAC
CLI Example:
.. code-block:: bash
salt-run drac.reboot example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powercycle')
if 'successful' in stdout.readline():
log.info('powercycle successful')
else:
log.error('powercycle racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
|
Reboot a server using the Dell DRAC
CLI Example:
.. code-block:: bash
salt-run drac.reboot example.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/drac.py#L124-L148
|
[
"def __connect(hostname, timeout=20, username=None, password=None):\n '''\n Connect to the DRAC\n '''\n drac_cred = __opts__.get('drac')\n err_msg = 'No drac login credentials found. Please add the \\'username\\' and \\'password\\' ' \\\n 'fields beneath a \\'drac\\' key in the master configuration file. Or you can ' \\\n 'pass in a username and password as kwargs at the CLI.'\n\n if not username:\n if drac_cred is None:\n log.error(err_msg)\n return False\n username = drac_cred.get('username', None)\n if not password:\n if drac_cred is None:\n log.error(err_msg)\n return False\n password = drac_cred.get('password', None)\n\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n try:\n client.connect(hostname, username=username, password=password, timeout=timeout)\n except Exception as e:\n log.error('Unable to connect to %s: %s', hostname, e)\n return False\n\n return client\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC from the Master
The login credentials need to be configured in the Salt master
configuration file.
.. code-block: yaml
drac:
username: admin
password: secret
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import 3rd-party libs
try:
import paramiko
HAS_PARAMIKO = True
except ImportError:
HAS_PARAMIKO = False
log = logging.getLogger(__name__)
def __virtual__():
if HAS_PARAMIKO:
return True
return False, 'The drac runner module cannot be loaded: paramiko package is not installed.'
def __connect(hostname, timeout=20, username=None, password=None):
'''
Connect to the DRAC
'''
drac_cred = __opts__.get('drac')
err_msg = 'No drac login credentials found. Please add the \'username\' and \'password\' ' \
'fields beneath a \'drac\' key in the master configuration file. Or you can ' \
'pass in a username and password as kwargs at the CLI.'
if not username:
if drac_cred is None:
log.error(err_msg)
return False
username = drac_cred.get('username', None)
if not password:
if drac_cred is None:
log.error(err_msg)
return False
password = drac_cred.get('password', None)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, username=username, password=password, timeout=timeout)
except Exception as e:
log.error('Unable to connect to %s: %s', hostname, e)
return False
return client
def __version(client):
'''
Grab DRAC version
'''
versions = {9: 'CMC',
8: 'iDRAC6',
10: 'iDRAC6',
11: 'iDRAC6',
16: 'iDRAC7',
17: 'iDRAC7'}
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm getconfig -g idRacInfo')
for i in stdout.readlines():
if i[2:].startswith('idRacType'):
return versions.get(int(i[2:].split('=')[1]), None)
return None
def pxe(hostname, timeout=20, username=None, password=None):
'''
Connect to the Dell DRAC and have the boot order set to PXE
and power cycle the system to PXE boot
CLI Example:
.. code-block:: bash
salt-run drac.pxe example.com
'''
_cmds = [
'racadm config -g cfgServerInfo -o cfgServerFirstBootDevice pxe',
'racadm config -g cfgServerInfo -o cfgServerBootOnce 1',
'racadm serveraction powercycle',
]
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
for i, cmd in enumerate(_cmds, 1):
log.info('Executing command %s', i)
(stdin, stdout, stderr) = client.exec_command(cmd)
if 'successful' in stdout.readline():
log.info('Executing command: %s', cmd)
else:
log.error('Unable to execute: %s', cmd)
return False
return True
def poweroff(hostname, timeout=20, username=None, password=None):
'''
Power server off
CLI Example:
.. code-block:: bash
salt-run drac.poweroff example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerdown')
if 'successful' in stdout.readline():
log.info('powerdown successful')
else:
log.error('powerdown racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def poweron(hostname, timeout=20, username=None, password=None):
'''
Power server on
CLI Example:
.. code-block:: bash
salt-run drac.poweron example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerup')
if 'successful' in stdout.readline():
log.info('powerup successful')
else:
log.error('powerup racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def version(hostname, timeout=20, username=None, password=None):
'''
Display the version of DRAC
CLI Example:
.. code-block:: bash
salt-run drac.version example.com
'''
return __version(__connect(hostname, timeout, username, password))
|
saltstack/salt
|
salt/runners/drac.py
|
version
|
python
|
def version(hostname, timeout=20, username=None, password=None):
'''
Display the version of DRAC
CLI Example:
.. code-block:: bash
salt-run drac.version example.com
'''
return __version(__connect(hostname, timeout, username, password))
|
Display the version of DRAC
CLI Example:
.. code-block:: bash
salt-run drac.version example.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/drac.py#L205-L215
|
[
"def __connect(hostname, timeout=20, username=None, password=None):\n '''\n Connect to the DRAC\n '''\n drac_cred = __opts__.get('drac')\n err_msg = 'No drac login credentials found. Please add the \\'username\\' and \\'password\\' ' \\\n 'fields beneath a \\'drac\\' key in the master configuration file. Or you can ' \\\n 'pass in a username and password as kwargs at the CLI.'\n\n if not username:\n if drac_cred is None:\n log.error(err_msg)\n return False\n username = drac_cred.get('username', None)\n if not password:\n if drac_cred is None:\n log.error(err_msg)\n return False\n password = drac_cred.get('password', None)\n\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n try:\n client.connect(hostname, username=username, password=password, timeout=timeout)\n except Exception as e:\n log.error('Unable to connect to %s: %s', hostname, e)\n return False\n\n return client\n",
"def __version(client):\n '''\n Grab DRAC version\n '''\n versions = {9: 'CMC',\n 8: 'iDRAC6',\n 10: 'iDRAC6',\n 11: 'iDRAC6',\n 16: 'iDRAC7',\n 17: 'iDRAC7'}\n\n if isinstance(client, paramiko.SSHClient):\n (stdin, stdout, stderr) = client.exec_command('racadm getconfig -g idRacInfo')\n\n for i in stdout.readlines():\n if i[2:].startswith('idRacType'):\n return versions.get(int(i[2:].split('=')[1]), None)\n\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Dell DRAC from the Master
The login credentials need to be configured in the Salt master
configuration file.
.. code-block: yaml
drac:
username: admin
password: secret
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import 3rd-party libs
try:
import paramiko
HAS_PARAMIKO = True
except ImportError:
HAS_PARAMIKO = False
log = logging.getLogger(__name__)
def __virtual__():
if HAS_PARAMIKO:
return True
return False, 'The drac runner module cannot be loaded: paramiko package is not installed.'
def __connect(hostname, timeout=20, username=None, password=None):
'''
Connect to the DRAC
'''
drac_cred = __opts__.get('drac')
err_msg = 'No drac login credentials found. Please add the \'username\' and \'password\' ' \
'fields beneath a \'drac\' key in the master configuration file. Or you can ' \
'pass in a username and password as kwargs at the CLI.'
if not username:
if drac_cred is None:
log.error(err_msg)
return False
username = drac_cred.get('username', None)
if not password:
if drac_cred is None:
log.error(err_msg)
return False
password = drac_cred.get('password', None)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, username=username, password=password, timeout=timeout)
except Exception as e:
log.error('Unable to connect to %s: %s', hostname, e)
return False
return client
def __version(client):
'''
Grab DRAC version
'''
versions = {9: 'CMC',
8: 'iDRAC6',
10: 'iDRAC6',
11: 'iDRAC6',
16: 'iDRAC7',
17: 'iDRAC7'}
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm getconfig -g idRacInfo')
for i in stdout.readlines():
if i[2:].startswith('idRacType'):
return versions.get(int(i[2:].split('=')[1]), None)
return None
def pxe(hostname, timeout=20, username=None, password=None):
'''
Connect to the Dell DRAC and have the boot order set to PXE
and power cycle the system to PXE boot
CLI Example:
.. code-block:: bash
salt-run drac.pxe example.com
'''
_cmds = [
'racadm config -g cfgServerInfo -o cfgServerFirstBootDevice pxe',
'racadm config -g cfgServerInfo -o cfgServerBootOnce 1',
'racadm serveraction powercycle',
]
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
for i, cmd in enumerate(_cmds, 1):
log.info('Executing command %s', i)
(stdin, stdout, stderr) = client.exec_command(cmd)
if 'successful' in stdout.readline():
log.info('Executing command: %s', cmd)
else:
log.error('Unable to execute: %s', cmd)
return False
return True
def reboot(hostname, timeout=20, username=None, password=None):
'''
Reboot a server using the Dell DRAC
CLI Example:
.. code-block:: bash
salt-run drac.reboot example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powercycle')
if 'successful' in stdout.readline():
log.info('powercycle successful')
else:
log.error('powercycle racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def poweroff(hostname, timeout=20, username=None, password=None):
'''
Power server off
CLI Example:
.. code-block:: bash
salt-run drac.poweroff example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerdown')
if 'successful' in stdout.readline():
log.info('powerdown successful')
else:
log.error('powerdown racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
def poweron(hostname, timeout=20, username=None, password=None):
'''
Power server on
CLI Example:
.. code-block:: bash
salt-run drac.poweron example.com
'''
client = __connect(hostname, timeout, username, password)
if isinstance(client, paramiko.SSHClient):
(stdin, stdout, stderr) = client.exec_command('racadm serveraction powerup')
if 'successful' in stdout.readline():
log.info('powerup successful')
else:
log.error('powerup racadm command failed')
return False
else:
log.error('client was not of type paramiko.SSHClient')
return False
return True
|
saltstack/salt
|
salt/beacons/glxinfo.py
|
beacon
|
python
|
def beacon(config):
'''
Emit the status of a connected display to the minion
Mainly this is used to detect when the display fails to connect
for whatever reason.
.. code-block:: yaml
beacons:
glxinfo:
- user: frank
- screen_event: True
'''
log.trace('glxinfo beacon starting')
ret = []
_config = {}
list(map(_config.update, config))
retcode = __salt__['cmd.retcode']('DISPLAY=:0 glxinfo',
runas=_config['user'], python_shell=True)
if 'screen_event' in _config and _config['screen_event']:
last_value = last_state.get('screen_available', False)
screen_available = retcode == 0
if last_value != screen_available or 'screen_available' not in last_state:
ret.append({'tag': 'screen_event', 'screen_available': screen_available})
last_state['screen_available'] = screen_available
return ret
|
Emit the status of a connected display to the minion
Mainly this is used to detect when the display fails to connect
for whatever reason.
.. code-block:: yaml
beacons:
glxinfo:
- user: frank
- screen_event: True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/glxinfo.py#L49-L82
| null |
# -*- coding: utf-8 -*-
'''
Beacon to emit when a display is available to a linux machine
.. versionadded:: 2016.3.0
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
# Salt libs
import salt.utils.path
from salt.ext.six.moves import map
log = logging.getLogger(__name__)
__virtualname__ = 'glxinfo'
last_state = {}
def __virtual__():
which_result = salt.utils.path.which('glxinfo')
if which_result is None:
return False
else:
return __virtualname__
def validate(config):
'''
Validate the beacon configuration
'''
# Configuration for glxinfo beacon should be a dictionary
if not isinstance(config, list):
return False, ('Configuration for glxinfo beacon must be a list.')
_config = {}
list(map(_config.update, config))
if 'user' not in _config:
return False, ('Configuration for glxinfo beacon must '
'include a user as glxinfo is not available to root.')
return True, 'Valid beacon configuration'
|
saltstack/salt
|
salt/runners/config.py
|
get
|
python
|
def get(key, default='', delimiter=':'):
'''
Retrieve master config options, with optional nesting via the delimiter
argument.
**Arguments**
default
If the key is not found, the default will be returned instead
delimiter
Override the delimiter used to separate nested levels of a data
structure.
CLI Example:
.. code-block:: bash
salt-run config.get gitfs_remotes
salt-run config.get file_roots:base
salt-run config.get file_roots,base delimiter=','
'''
ret = salt.utils.data.traverse_dict_and_list(__opts__, key, default='_|-', delimiter=delimiter)
if ret == '_|-':
return default
else:
return salt.utils.sdb.sdb_get(ret, __opts__)
|
Retrieve master config options, with optional nesting via the delimiter
argument.
**Arguments**
default
If the key is not found, the default will be returned instead
delimiter
Override the delimiter used to separate nested levels of a data
structure.
CLI Example:
.. code-block:: bash
salt-run config.get gitfs_remotes
salt-run config.get file_roots:base
salt-run config.get file_roots,base delimiter=','
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/config.py#L12-L40
|
[
"def sdb_get(uri, opts, utils=None):\n '''\n Get a value from a db, using a uri in the form of ``sdb://<profile>/<key>``. If\n the uri provided does not start with ``sdb://``, then it will be returned as-is.\n '''\n if not isinstance(uri, string_types) or not uri.startswith('sdb://'):\n return uri\n\n if utils is None:\n utils = salt.loader.utils(opts)\n\n sdlen = len('sdb://')\n indx = uri.find('/', sdlen)\n\n if (indx == -1) or not uri[(indx + 1):]:\n return uri\n\n profile = opts.get(uri[sdlen:indx], {})\n if not profile:\n profile = opts.get('pillar', {}).get(uri[sdlen:indx], {})\n if 'driver' not in profile:\n return uri\n\n fun = '{0}.get'.format(profile['driver'])\n query = uri[indx+1:]\n\n loaded_db = salt.loader.sdb(opts, fun, utils=utils)\n return loaded_db[fun](query, profile=profile)\n"
] |
# -*- coding: utf-8 -*-
'''
This runner is designed to mirror the execution module config.py, but for
master settings
'''
from __future__ import absolute_import, print_function, unicode_literals
import salt.utils.data
import salt.utils.sdb
|
saltstack/salt
|
salt/modules/namecheap_ssl.py
|
reissue
|
python
|
def reissue(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Reissues a purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/reissue.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.reissue my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.reissue', "SSLReissueResult", csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
|
Reissues a purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/reissue.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.reissue my-csr-file my-cert-id apachessl
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_ssl.py#L58-L128
|
[
"def __get_certificates(command,\n result_tag_name,\n csr_file,\n certificate_id,\n web_server_type,\n approver_email,\n http_dc_validation,\n kwargs):\n\n web_server_types = ('apacheopenssl',\n 'apachessl',\n 'apacheraven',\n 'apachessleay',\n 'c2net',\n 'ibmhttp',\n 'iplanet',\n 'domino',\n 'dominogo4625',\n 'dominogo4626',\n 'netscape',\n 'zeusv3',\n 'apache2',\n 'apacheapachessl',\n 'cobaltseries',\n 'cpanel',\n 'ensim',\n 'hsphere',\n 'ipswitch',\n 'plesk',\n 'tomcat',\n 'weblogic',\n 'website',\n 'webstar',\n 'iis',\n 'other',\n 'iis4',\n 'iis5',\n )\n\n if web_server_type not in web_server_types:\n log.error('Invalid option for web_server_type=%s', web_server_type)\n raise Exception('Invalid option for web_server_type=' + web_server_type)\n\n if approver_email is not None and http_dc_validation:\n log.error('approver_email and http_dc_validation cannot both have values')\n raise Exception('approver_email and http_dc_validation cannot both have values')\n\n if approver_email is None and not http_dc_validation:\n log.error('approver_email or http_dc_validation must have a value')\n raise Exception('approver_email or http_dc_validation must have a value')\n\n opts = salt.utils.namecheap.get_opts(command)\n\n with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:\n opts['csr'] = salt.utils.stringutils.to_unicode(\n csr_handle.read()\n )\n\n opts['CertificateID'] = certificate_id\n opts['WebServerType'] = web_server_type\n if approver_email is not None:\n opts['ApproverEmail'] = approver_email\n\n if http_dc_validation:\n opts['HTTPDCValidation'] = 'True'\n\n for key, value in six.iteritems(kwargs):\n opts[key] = value\n\n response_xml = salt.utils.namecheap.post_request(opts)\n\n if response_xml is None:\n return {}\n\n sslresult = response_xml.getElementsByTagName(result_tag_name)[0]\n result = salt.utils.namecheap.atts_to_dict(sslresult)\n\n if http_dc_validation:\n validation_tag = sslresult.getElementsByTagName('HttpDCValidation')\n if validation_tag:\n validation_tag = validation_tag[0]\n\n if validation_tag.getAttribute('ValueAvailable').lower() == 'true':\n validation_dict = {'filename': validation_tag.getElementsByTagName('FileName')[0].childNodes[0].data,\n 'filecontent': validation_tag.getElementsByTagName('FileContent')[0].childNodes[\n 0].data}\n result['httpdcvalidation'] = validation_dict\n\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
Namecheap SSL Certificate Management
.. versionadded:: 2017.7.0
Prerequisites
-------------
This module uses the ``requests`` Python module to communicate to the namecheap
API.
Configuration
-------------
The Namecheap username, API key and URL should be set in the minion configuration
file, or in the Pillar data.
.. code-block:: yaml
namecheap.name: companyname
namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3
namecheap.client_ip: 162.155.30.172
#Real url
namecheap.url: https://api.namecheap.com/xml.response
#Sandbox url
#namecheap.url: https://api.sandbox.namecheap.xml.response
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.files
import salt.utils.stringutils
try:
import salt.utils.namecheap
CAN_USE_NAMECHEAP = True
except ImportError:
CAN_USE_NAMECHEAP = False
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Check to make sure requests and xml are installed and requests
'''
if CAN_USE_NAMECHEAP:
return 'namecheap_ssl'
return False
def activate(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Activates a newly-purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/activate.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.activate my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.activate', 'SSLActivateResult', csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def __get_certificates(command,
result_tag_name,
csr_file,
certificate_id,
web_server_type,
approver_email,
http_dc_validation,
kwargs):
web_server_types = ('apacheopenssl',
'apachessl',
'apacheraven',
'apachessleay',
'c2net',
'ibmhttp',
'iplanet',
'domino',
'dominogo4625',
'dominogo4626',
'netscape',
'zeusv3',
'apache2',
'apacheapachessl',
'cobaltseries',
'cpanel',
'ensim',
'hsphere',
'ipswitch',
'plesk',
'tomcat',
'weblogic',
'website',
'webstar',
'iis',
'other',
'iis4',
'iis5',
)
if web_server_type not in web_server_types:
log.error('Invalid option for web_server_type=%s', web_server_type)
raise Exception('Invalid option for web_server_type=' + web_server_type)
if approver_email is not None and http_dc_validation:
log.error('approver_email and http_dc_validation cannot both have values')
raise Exception('approver_email and http_dc_validation cannot both have values')
if approver_email is None and not http_dc_validation:
log.error('approver_email or http_dc_validation must have a value')
raise Exception('approver_email or http_dc_validation must have a value')
opts = salt.utils.namecheap.get_opts(command)
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateID'] = certificate_id
opts['WebServerType'] = web_server_type
if approver_email is not None:
opts['ApproverEmail'] = approver_email
if http_dc_validation:
opts['HTTPDCValidation'] = 'True'
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslresult = response_xml.getElementsByTagName(result_tag_name)[0]
result = salt.utils.namecheap.atts_to_dict(sslresult)
if http_dc_validation:
validation_tag = sslresult.getElementsByTagName('HttpDCValidation')
if validation_tag:
validation_tag = validation_tag[0]
if validation_tag.getAttribute('ValueAvailable').lower() == 'true':
validation_dict = {'filename': validation_tag.getElementsByTagName('FileName')[0].childNodes[0].data,
'filecontent': validation_tag.getElementsByTagName('FileContent')[0].childNodes[
0].data}
result['httpdcvalidation'] = validation_dict
return result
def renew(years, certificate_id, certificate_type, promotion_code=None):
'''
Renews an SSL certificate if it is ACTIVE and Expires <= 30 days. Returns
the following information:
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
years : 1
Number of years to register
certificate_id
Unique ID of the SSL certificate you wish to renew
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when renewing the certificate
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.renew 1 my-cert-id RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.renew')
opts['Years'] = six.text_type(years)
opts['CertificateID'] = six.text_type(certificate_id)
opts['SSLType'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslrenewresult = response_xml.getElementsByTagName('SSLRenewResult')[0]
return salt.utils.namecheap.atts_to_dict(sslrenewresult)
def create(years, certificate_type, promotion_code=None, sans_to_add=None):
'''
Creates a new SSL certificate. Returns the following information:
- Whether or not the SSL order was successful
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
- The date on which the certificate was created
- The date on which the certificate will expire
- The type of SSL certificate
- The number of years for which the certificate was purchased
- The current status of the SSL certificate
years : 1
Number of years to register
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when creating the certificate
sans_to_add : 0
This parameter defines the number of add-on domains to be purchased in
addition to the default number of domains included with a multi-domain
certificate. Each certificate that supports SANs has the default number
of domains included. You may check the default number of domains
included and the maximum number of domains that can be added to it in
the table below.
+----------+----------------+----------------------+-------------------+----------------+
| Provider | Product name | Default number of | Maximum number of | Maximum number |
| | | domains (domain from | total domains | of domains |
| | | CSR is counted here) | | that can be |
| | | | | passed in |
| | | | | sans_to_add |
| | | | | parameter |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | PositiveSSL | 3 | 100 | 97 |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Multi-Domain | 3 | 100 | 97 |
| | SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | EV Multi- | 3 | 100 | 97 |
| | Domain SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Unified | 3 | 100 | 97 |
| | Communications | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | QuickSSL | 1 | 1 domain + | The only |
| | Premium | | 4 subdomains | supported |
| | | | | value is 4 |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True | 5 | 25 | 20 |
| | BusinessID | | | |
| | with EV | | | |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True Business | 5 | 25 | 20 |
| | ID Multi- | | | |
| | Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server with | | | |
| | EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SGC Supercerts | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro | | | |
+----------+----------------+----------------------+-------------------+----------------+
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.create 2 RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.create')
opts['Years'] = years
opts['Type'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
if sans_to_add is not None:
opts['SANStoADD'] = sans_to_add
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslcreateresult = response_xml.getElementsByTagName('SSLCreateResult')[0]
sslcertinfo = sslcreateresult.getElementsByTagName('SSLCertificate')[0]
result = salt.utils.namecheap.atts_to_dict(sslcreateresult)
result.update(salt.utils.namecheap.atts_to_dict(sslcertinfo))
return result
def parse_csr(csr_file, certificate_type, http_dc_validation=False):
'''
Parses the CSR. Returns a dictionary of result values.
csr_file
Path to Certificate Signing Request file
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
http_dc_validation : False
Set to ``True`` if a Comodo certificate and validation should be
done with files instead of emails and to return the info to do so
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.parse_csr my-csr-file PremiumSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
opts = salt.utils.namecheap.get_opts('namecheap.ssl.parseCSR')
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateType'] = certificate_type
if http_dc_validation:
opts['HTTPDCValidation'] = 'true'
response_xml = salt.utils.namecheap.post_request(opts)
sslparseresult = response_xml.getElementsByTagName('SSLParseCSRResult')[0]
return salt.utils.namecheap.xml_to_dict(sslparseresult)
def get_list(**kwargs):
'''
Returns a list of SSL certificates for a particular user
ListType : All
Possible values:
- All
- Processing
- EmailSent
- TechnicalProblem
- InProgress
- Completed
- Deactivated
- Active
- Cancelled
- NewPurchase
- NewRenewal
SearchTerm
Keyword to look for on the SSL list
Page : 1
Page number to return
PageSize : 20
Total number of SSL certificates to display per page (minimum:
``10``, maximum: ``100``)
SoryBy
One of ``PURCHASEDATE``, ``PURCHASEDATE_DESC``, ``SSLTYPE``,
``SSLTYPE_DESC``, ``EXPIREDATETIME``, ``EXPIREDATETIME_DESC``,
``Host_Name``, or ``Host_Name_DESC``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_list Processing
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getList')
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return []
ssllistresult = response_xml.getElementsByTagName('SSLListResult')[0]
result = []
for e in ssllistresult.getElementsByTagName('SSL'):
ssl = salt.utils.namecheap.atts_to_dict(e)
result.append(ssl)
return result
def get_info(certificate_id, returncertificate=False, returntype=None):
'''
Retrieves information about the requested SSL certificate. Returns a
dictionary of information about the SSL certificate with two keys:
- **ssl** - Contains the metadata information
- **certificate** - Contains the details for the certificate such as the
CSR, Approver, and certificate data
certificate_id
Unique ID of the SSL certificate
returncertificate : False
Set to ``True`` to ask for the certificate in response
returntype
Optional type for the returned certificate. Can be either "Individual"
(for X.509 format) or "PKCS7"
.. note::
Required if ``returncertificate`` is ``True``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_info my-cert-id
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getinfo')
opts['certificateID'] = certificate_id
if returncertificate:
opts['returncertificate'] = "true"
if returntype is None:
log.error('returntype must be specified when returncertificate is set to True')
raise Exception('returntype must be specified when returncertificate is set to True')
if returntype not in ["Individual", "PKCS7"]:
log.error('returntype must be specified as Individual or PKCS7, not %s', returntype)
raise Exception('returntype must be specified as Individual or PKCS7, not ' + returntype)
opts['returntype'] = returntype
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return {}
sslinforesult = response_xml.getElementsByTagName('SSLGetInfoResult')[0]
return salt.utils.namecheap.xml_to_dict(sslinforesult)
|
saltstack/salt
|
salt/modules/namecheap_ssl.py
|
renew
|
python
|
def renew(years, certificate_id, certificate_type, promotion_code=None):
'''
Renews an SSL certificate if it is ACTIVE and Expires <= 30 days. Returns
the following information:
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
years : 1
Number of years to register
certificate_id
Unique ID of the SSL certificate you wish to renew
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when renewing the certificate
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.renew 1 my-cert-id RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.renew')
opts['Years'] = six.text_type(years)
opts['CertificateID'] = six.text_type(certificate_id)
opts['SSLType'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslrenewresult = response_xml.getElementsByTagName('SSLRenewResult')[0]
return salt.utils.namecheap.atts_to_dict(sslrenewresult)
|
Renews an SSL certificate if it is ACTIVE and Expires <= 30 days. Returns
the following information:
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
years : 1
Number of years to register
certificate_id
Unique ID of the SSL certificate you wish to renew
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when renewing the certificate
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.renew 1 my-cert-id RapidSSL
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_ssl.py#L295-L407
|
[
"def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n",
"def post_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.post(namecheap_url, data=opts, timeout=45))\n",
"def atts_to_dict(xml):\n result = {}\n if xml.attributes is not None:\n for key, value in xml.attributes.items():\n result[key.lower()] = string_to_value(value)\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
Namecheap SSL Certificate Management
.. versionadded:: 2017.7.0
Prerequisites
-------------
This module uses the ``requests`` Python module to communicate to the namecheap
API.
Configuration
-------------
The Namecheap username, API key and URL should be set in the minion configuration
file, or in the Pillar data.
.. code-block:: yaml
namecheap.name: companyname
namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3
namecheap.client_ip: 162.155.30.172
#Real url
namecheap.url: https://api.namecheap.com/xml.response
#Sandbox url
#namecheap.url: https://api.sandbox.namecheap.xml.response
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.files
import salt.utils.stringutils
try:
import salt.utils.namecheap
CAN_USE_NAMECHEAP = True
except ImportError:
CAN_USE_NAMECHEAP = False
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Check to make sure requests and xml are installed and requests
'''
if CAN_USE_NAMECHEAP:
return 'namecheap_ssl'
return False
def reissue(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Reissues a purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/reissue.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.reissue my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.reissue', "SSLReissueResult", csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def activate(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Activates a newly-purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/activate.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.activate my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.activate', 'SSLActivateResult', csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def __get_certificates(command,
result_tag_name,
csr_file,
certificate_id,
web_server_type,
approver_email,
http_dc_validation,
kwargs):
web_server_types = ('apacheopenssl',
'apachessl',
'apacheraven',
'apachessleay',
'c2net',
'ibmhttp',
'iplanet',
'domino',
'dominogo4625',
'dominogo4626',
'netscape',
'zeusv3',
'apache2',
'apacheapachessl',
'cobaltseries',
'cpanel',
'ensim',
'hsphere',
'ipswitch',
'plesk',
'tomcat',
'weblogic',
'website',
'webstar',
'iis',
'other',
'iis4',
'iis5',
)
if web_server_type not in web_server_types:
log.error('Invalid option for web_server_type=%s', web_server_type)
raise Exception('Invalid option for web_server_type=' + web_server_type)
if approver_email is not None and http_dc_validation:
log.error('approver_email and http_dc_validation cannot both have values')
raise Exception('approver_email and http_dc_validation cannot both have values')
if approver_email is None and not http_dc_validation:
log.error('approver_email or http_dc_validation must have a value')
raise Exception('approver_email or http_dc_validation must have a value')
opts = salt.utils.namecheap.get_opts(command)
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateID'] = certificate_id
opts['WebServerType'] = web_server_type
if approver_email is not None:
opts['ApproverEmail'] = approver_email
if http_dc_validation:
opts['HTTPDCValidation'] = 'True'
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslresult = response_xml.getElementsByTagName(result_tag_name)[0]
result = salt.utils.namecheap.atts_to_dict(sslresult)
if http_dc_validation:
validation_tag = sslresult.getElementsByTagName('HttpDCValidation')
if validation_tag:
validation_tag = validation_tag[0]
if validation_tag.getAttribute('ValueAvailable').lower() == 'true':
validation_dict = {'filename': validation_tag.getElementsByTagName('FileName')[0].childNodes[0].data,
'filecontent': validation_tag.getElementsByTagName('FileContent')[0].childNodes[
0].data}
result['httpdcvalidation'] = validation_dict
return result
def create(years, certificate_type, promotion_code=None, sans_to_add=None):
'''
Creates a new SSL certificate. Returns the following information:
- Whether or not the SSL order was successful
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
- The date on which the certificate was created
- The date on which the certificate will expire
- The type of SSL certificate
- The number of years for which the certificate was purchased
- The current status of the SSL certificate
years : 1
Number of years to register
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when creating the certificate
sans_to_add : 0
This parameter defines the number of add-on domains to be purchased in
addition to the default number of domains included with a multi-domain
certificate. Each certificate that supports SANs has the default number
of domains included. You may check the default number of domains
included and the maximum number of domains that can be added to it in
the table below.
+----------+----------------+----------------------+-------------------+----------------+
| Provider | Product name | Default number of | Maximum number of | Maximum number |
| | | domains (domain from | total domains | of domains |
| | | CSR is counted here) | | that can be |
| | | | | passed in |
| | | | | sans_to_add |
| | | | | parameter |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | PositiveSSL | 3 | 100 | 97 |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Multi-Domain | 3 | 100 | 97 |
| | SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | EV Multi- | 3 | 100 | 97 |
| | Domain SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Unified | 3 | 100 | 97 |
| | Communications | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | QuickSSL | 1 | 1 domain + | The only |
| | Premium | | 4 subdomains | supported |
| | | | | value is 4 |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True | 5 | 25 | 20 |
| | BusinessID | | | |
| | with EV | | | |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True Business | 5 | 25 | 20 |
| | ID Multi- | | | |
| | Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server with | | | |
| | EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SGC Supercerts | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro | | | |
+----------+----------------+----------------------+-------------------+----------------+
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.create 2 RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.create')
opts['Years'] = years
opts['Type'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
if sans_to_add is not None:
opts['SANStoADD'] = sans_to_add
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslcreateresult = response_xml.getElementsByTagName('SSLCreateResult')[0]
sslcertinfo = sslcreateresult.getElementsByTagName('SSLCertificate')[0]
result = salt.utils.namecheap.atts_to_dict(sslcreateresult)
result.update(salt.utils.namecheap.atts_to_dict(sslcertinfo))
return result
def parse_csr(csr_file, certificate_type, http_dc_validation=False):
'''
Parses the CSR. Returns a dictionary of result values.
csr_file
Path to Certificate Signing Request file
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
http_dc_validation : False
Set to ``True`` if a Comodo certificate and validation should be
done with files instead of emails and to return the info to do so
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.parse_csr my-csr-file PremiumSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
opts = salt.utils.namecheap.get_opts('namecheap.ssl.parseCSR')
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateType'] = certificate_type
if http_dc_validation:
opts['HTTPDCValidation'] = 'true'
response_xml = salt.utils.namecheap.post_request(opts)
sslparseresult = response_xml.getElementsByTagName('SSLParseCSRResult')[0]
return salt.utils.namecheap.xml_to_dict(sslparseresult)
def get_list(**kwargs):
'''
Returns a list of SSL certificates for a particular user
ListType : All
Possible values:
- All
- Processing
- EmailSent
- TechnicalProblem
- InProgress
- Completed
- Deactivated
- Active
- Cancelled
- NewPurchase
- NewRenewal
SearchTerm
Keyword to look for on the SSL list
Page : 1
Page number to return
PageSize : 20
Total number of SSL certificates to display per page (minimum:
``10``, maximum: ``100``)
SoryBy
One of ``PURCHASEDATE``, ``PURCHASEDATE_DESC``, ``SSLTYPE``,
``SSLTYPE_DESC``, ``EXPIREDATETIME``, ``EXPIREDATETIME_DESC``,
``Host_Name``, or ``Host_Name_DESC``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_list Processing
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getList')
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return []
ssllistresult = response_xml.getElementsByTagName('SSLListResult')[0]
result = []
for e in ssllistresult.getElementsByTagName('SSL'):
ssl = salt.utils.namecheap.atts_to_dict(e)
result.append(ssl)
return result
def get_info(certificate_id, returncertificate=False, returntype=None):
'''
Retrieves information about the requested SSL certificate. Returns a
dictionary of information about the SSL certificate with two keys:
- **ssl** - Contains the metadata information
- **certificate** - Contains the details for the certificate such as the
CSR, Approver, and certificate data
certificate_id
Unique ID of the SSL certificate
returncertificate : False
Set to ``True`` to ask for the certificate in response
returntype
Optional type for the returned certificate. Can be either "Individual"
(for X.509 format) or "PKCS7"
.. note::
Required if ``returncertificate`` is ``True``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_info my-cert-id
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getinfo')
opts['certificateID'] = certificate_id
if returncertificate:
opts['returncertificate'] = "true"
if returntype is None:
log.error('returntype must be specified when returncertificate is set to True')
raise Exception('returntype must be specified when returncertificate is set to True')
if returntype not in ["Individual", "PKCS7"]:
log.error('returntype must be specified as Individual or PKCS7, not %s', returntype)
raise Exception('returntype must be specified as Individual or PKCS7, not ' + returntype)
opts['returntype'] = returntype
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return {}
sslinforesult = response_xml.getElementsByTagName('SSLGetInfoResult')[0]
return salt.utils.namecheap.xml_to_dict(sslinforesult)
|
saltstack/salt
|
salt/modules/namecheap_ssl.py
|
create
|
python
|
def create(years, certificate_type, promotion_code=None, sans_to_add=None):
'''
Creates a new SSL certificate. Returns the following information:
- Whether or not the SSL order was successful
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
- The date on which the certificate was created
- The date on which the certificate will expire
- The type of SSL certificate
- The number of years for which the certificate was purchased
- The current status of the SSL certificate
years : 1
Number of years to register
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when creating the certificate
sans_to_add : 0
This parameter defines the number of add-on domains to be purchased in
addition to the default number of domains included with a multi-domain
certificate. Each certificate that supports SANs has the default number
of domains included. You may check the default number of domains
included and the maximum number of domains that can be added to it in
the table below.
+----------+----------------+----------------------+-------------------+----------------+
| Provider | Product name | Default number of | Maximum number of | Maximum number |
| | | domains (domain from | total domains | of domains |
| | | CSR is counted here) | | that can be |
| | | | | passed in |
| | | | | sans_to_add |
| | | | | parameter |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | PositiveSSL | 3 | 100 | 97 |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Multi-Domain | 3 | 100 | 97 |
| | SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | EV Multi- | 3 | 100 | 97 |
| | Domain SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Unified | 3 | 100 | 97 |
| | Communications | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | QuickSSL | 1 | 1 domain + | The only |
| | Premium | | 4 subdomains | supported |
| | | | | value is 4 |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True | 5 | 25 | 20 |
| | BusinessID | | | |
| | with EV | | | |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True Business | 5 | 25 | 20 |
| | ID Multi- | | | |
| | Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server with | | | |
| | EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SGC Supercerts | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro | | | |
+----------+----------------+----------------------+-------------------+----------------+
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.create 2 RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.create')
opts['Years'] = years
opts['Type'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
if sans_to_add is not None:
opts['SANStoADD'] = sans_to_add
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslcreateresult = response_xml.getElementsByTagName('SSLCreateResult')[0]
sslcertinfo = sslcreateresult.getElementsByTagName('SSLCertificate')[0]
result = salt.utils.namecheap.atts_to_dict(sslcreateresult)
result.update(salt.utils.namecheap.atts_to_dict(sslcertinfo))
return result
|
Creates a new SSL certificate. Returns the following information:
- Whether or not the SSL order was successful
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
- The date on which the certificate was created
- The date on which the certificate will expire
- The type of SSL certificate
- The number of years for which the certificate was purchased
- The current status of the SSL certificate
years : 1
Number of years to register
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when creating the certificate
sans_to_add : 0
This parameter defines the number of add-on domains to be purchased in
addition to the default number of domains included with a multi-domain
certificate. Each certificate that supports SANs has the default number
of domains included. You may check the default number of domains
included and the maximum number of domains that can be added to it in
the table below.
+----------+----------------+----------------------+-------------------+----------------+
| Provider | Product name | Default number of | Maximum number of | Maximum number |
| | | domains (domain from | total domains | of domains |
| | | CSR is counted here) | | that can be |
| | | | | passed in |
| | | | | sans_to_add |
| | | | | parameter |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | PositiveSSL | 3 | 100 | 97 |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Multi-Domain | 3 | 100 | 97 |
| | SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | EV Multi- | 3 | 100 | 97 |
| | Domain SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Unified | 3 | 100 | 97 |
| | Communications | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | QuickSSL | 1 | 1 domain + | The only |
| | Premium | | 4 subdomains | supported |
| | | | | value is 4 |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True | 5 | 25 | 20 |
| | BusinessID | | | |
| | with EV | | | |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True Business | 5 | 25 | 20 |
| | ID Multi- | | | |
| | Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server with | | | |
| | EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SGC Supercerts | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro | | | |
+----------+----------------+----------------------+-------------------+----------------+
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.create 2 RapidSSL
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_ssl.py#L410-L591
|
[
"def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n",
"def post_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.post(namecheap_url, data=opts, timeout=45))\n",
"def atts_to_dict(xml):\n result = {}\n if xml.attributes is not None:\n for key, value in xml.attributes.items():\n result[key.lower()] = string_to_value(value)\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
Namecheap SSL Certificate Management
.. versionadded:: 2017.7.0
Prerequisites
-------------
This module uses the ``requests`` Python module to communicate to the namecheap
API.
Configuration
-------------
The Namecheap username, API key and URL should be set in the minion configuration
file, or in the Pillar data.
.. code-block:: yaml
namecheap.name: companyname
namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3
namecheap.client_ip: 162.155.30.172
#Real url
namecheap.url: https://api.namecheap.com/xml.response
#Sandbox url
#namecheap.url: https://api.sandbox.namecheap.xml.response
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.files
import salt.utils.stringutils
try:
import salt.utils.namecheap
CAN_USE_NAMECHEAP = True
except ImportError:
CAN_USE_NAMECHEAP = False
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Check to make sure requests and xml are installed and requests
'''
if CAN_USE_NAMECHEAP:
return 'namecheap_ssl'
return False
def reissue(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Reissues a purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/reissue.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.reissue my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.reissue', "SSLReissueResult", csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def activate(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Activates a newly-purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/activate.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.activate my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.activate', 'SSLActivateResult', csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def __get_certificates(command,
result_tag_name,
csr_file,
certificate_id,
web_server_type,
approver_email,
http_dc_validation,
kwargs):
web_server_types = ('apacheopenssl',
'apachessl',
'apacheraven',
'apachessleay',
'c2net',
'ibmhttp',
'iplanet',
'domino',
'dominogo4625',
'dominogo4626',
'netscape',
'zeusv3',
'apache2',
'apacheapachessl',
'cobaltseries',
'cpanel',
'ensim',
'hsphere',
'ipswitch',
'plesk',
'tomcat',
'weblogic',
'website',
'webstar',
'iis',
'other',
'iis4',
'iis5',
)
if web_server_type not in web_server_types:
log.error('Invalid option for web_server_type=%s', web_server_type)
raise Exception('Invalid option for web_server_type=' + web_server_type)
if approver_email is not None and http_dc_validation:
log.error('approver_email and http_dc_validation cannot both have values')
raise Exception('approver_email and http_dc_validation cannot both have values')
if approver_email is None and not http_dc_validation:
log.error('approver_email or http_dc_validation must have a value')
raise Exception('approver_email or http_dc_validation must have a value')
opts = salt.utils.namecheap.get_opts(command)
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateID'] = certificate_id
opts['WebServerType'] = web_server_type
if approver_email is not None:
opts['ApproverEmail'] = approver_email
if http_dc_validation:
opts['HTTPDCValidation'] = 'True'
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslresult = response_xml.getElementsByTagName(result_tag_name)[0]
result = salt.utils.namecheap.atts_to_dict(sslresult)
if http_dc_validation:
validation_tag = sslresult.getElementsByTagName('HttpDCValidation')
if validation_tag:
validation_tag = validation_tag[0]
if validation_tag.getAttribute('ValueAvailable').lower() == 'true':
validation_dict = {'filename': validation_tag.getElementsByTagName('FileName')[0].childNodes[0].data,
'filecontent': validation_tag.getElementsByTagName('FileContent')[0].childNodes[
0].data}
result['httpdcvalidation'] = validation_dict
return result
def renew(years, certificate_id, certificate_type, promotion_code=None):
'''
Renews an SSL certificate if it is ACTIVE and Expires <= 30 days. Returns
the following information:
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
years : 1
Number of years to register
certificate_id
Unique ID of the SSL certificate you wish to renew
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when renewing the certificate
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.renew 1 my-cert-id RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.renew')
opts['Years'] = six.text_type(years)
opts['CertificateID'] = six.text_type(certificate_id)
opts['SSLType'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslrenewresult = response_xml.getElementsByTagName('SSLRenewResult')[0]
return salt.utils.namecheap.atts_to_dict(sslrenewresult)
def parse_csr(csr_file, certificate_type, http_dc_validation=False):
'''
Parses the CSR. Returns a dictionary of result values.
csr_file
Path to Certificate Signing Request file
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
http_dc_validation : False
Set to ``True`` if a Comodo certificate and validation should be
done with files instead of emails and to return the info to do so
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.parse_csr my-csr-file PremiumSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
opts = salt.utils.namecheap.get_opts('namecheap.ssl.parseCSR')
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateType'] = certificate_type
if http_dc_validation:
opts['HTTPDCValidation'] = 'true'
response_xml = salt.utils.namecheap.post_request(opts)
sslparseresult = response_xml.getElementsByTagName('SSLParseCSRResult')[0]
return salt.utils.namecheap.xml_to_dict(sslparseresult)
def get_list(**kwargs):
'''
Returns a list of SSL certificates for a particular user
ListType : All
Possible values:
- All
- Processing
- EmailSent
- TechnicalProblem
- InProgress
- Completed
- Deactivated
- Active
- Cancelled
- NewPurchase
- NewRenewal
SearchTerm
Keyword to look for on the SSL list
Page : 1
Page number to return
PageSize : 20
Total number of SSL certificates to display per page (minimum:
``10``, maximum: ``100``)
SoryBy
One of ``PURCHASEDATE``, ``PURCHASEDATE_DESC``, ``SSLTYPE``,
``SSLTYPE_DESC``, ``EXPIREDATETIME``, ``EXPIREDATETIME_DESC``,
``Host_Name``, or ``Host_Name_DESC``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_list Processing
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getList')
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return []
ssllistresult = response_xml.getElementsByTagName('SSLListResult')[0]
result = []
for e in ssllistresult.getElementsByTagName('SSL'):
ssl = salt.utils.namecheap.atts_to_dict(e)
result.append(ssl)
return result
def get_info(certificate_id, returncertificate=False, returntype=None):
'''
Retrieves information about the requested SSL certificate. Returns a
dictionary of information about the SSL certificate with two keys:
- **ssl** - Contains the metadata information
- **certificate** - Contains the details for the certificate such as the
CSR, Approver, and certificate data
certificate_id
Unique ID of the SSL certificate
returncertificate : False
Set to ``True`` to ask for the certificate in response
returntype
Optional type for the returned certificate. Can be either "Individual"
(for X.509 format) or "PKCS7"
.. note::
Required if ``returncertificate`` is ``True``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_info my-cert-id
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getinfo')
opts['certificateID'] = certificate_id
if returncertificate:
opts['returncertificate'] = "true"
if returntype is None:
log.error('returntype must be specified when returncertificate is set to True')
raise Exception('returntype must be specified when returncertificate is set to True')
if returntype not in ["Individual", "PKCS7"]:
log.error('returntype must be specified as Individual or PKCS7, not %s', returntype)
raise Exception('returntype must be specified as Individual or PKCS7, not ' + returntype)
opts['returntype'] = returntype
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return {}
sslinforesult = response_xml.getElementsByTagName('SSLGetInfoResult')[0]
return salt.utils.namecheap.xml_to_dict(sslinforesult)
|
saltstack/salt
|
salt/modules/namecheap_ssl.py
|
parse_csr
|
python
|
def parse_csr(csr_file, certificate_type, http_dc_validation=False):
'''
Parses the CSR. Returns a dictionary of result values.
csr_file
Path to Certificate Signing Request file
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
http_dc_validation : False
Set to ``True`` if a Comodo certificate and validation should be
done with files instead of emails and to return the info to do so
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.parse_csr my-csr-file PremiumSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
opts = salt.utils.namecheap.get_opts('namecheap.ssl.parseCSR')
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateType'] = certificate_type
if http_dc_validation:
opts['HTTPDCValidation'] = 'true'
response_xml = salt.utils.namecheap.post_request(opts)
sslparseresult = response_xml.getElementsByTagName('SSLParseCSRResult')[0]
return salt.utils.namecheap.xml_to_dict(sslparseresult)
|
Parses the CSR. Returns a dictionary of result values.
csr_file
Path to Certificate Signing Request file
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
http_dc_validation : False
Set to ``True`` if a Comodo certificate and validation should be
done with files instead of emails and to return the info to do so
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.parse_csr my-csr-file PremiumSSL
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_ssl.py#L594-L696
|
[
"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_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else 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 exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, 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 or bytearray')\n",
"def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n",
"def post_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.post(namecheap_url, data=opts, timeout=45))\n",
"def xml_to_dict(xml):\n if xml.nodeType == xml.CDATA_SECTION_NODE:\n return xml.data\n result = atts_to_dict(xml)\n if not [n for n in xml.childNodes if n.nodeType != xml.TEXT_NODE]:\n if result > 0:\n if xml.firstChild is not None and xml.firstChild.data:\n result['data'] = xml.firstChild.data\n elif xml.firstChild is not None and xml.firstChild.data:\n return xml.firstChild.data\n else:\n return None\n elif xml.childNodes.length == 1 and \\\n xml.childNodes[0].nodeType == xml.CDATA_SECTION_NODE:\n return xml.childNodes[0].data\n else:\n for n in xml.childNodes:\n if n.nodeType == xml.CDATA_SECTION_NODE:\n\n if xml.tagName.lower() in result:\n val = result[xml.tagName.lower()]\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(n.data)\n result[xml.tagName.lower()] = val\n else:\n result[xml.tagName.lower()] = n.data\n\n elif n.nodeType != xml.TEXT_NODE:\n\n if n.tagName.lower() in result:\n val = result[n.tagName.lower()]\n\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(xml_to_dict(n))\n result[n.tagName.lower()] = val\n else:\n result[n.tagName.lower()] = xml_to_dict(n)\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
Namecheap SSL Certificate Management
.. versionadded:: 2017.7.0
Prerequisites
-------------
This module uses the ``requests`` Python module to communicate to the namecheap
API.
Configuration
-------------
The Namecheap username, API key and URL should be set in the minion configuration
file, or in the Pillar data.
.. code-block:: yaml
namecheap.name: companyname
namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3
namecheap.client_ip: 162.155.30.172
#Real url
namecheap.url: https://api.namecheap.com/xml.response
#Sandbox url
#namecheap.url: https://api.sandbox.namecheap.xml.response
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.files
import salt.utils.stringutils
try:
import salt.utils.namecheap
CAN_USE_NAMECHEAP = True
except ImportError:
CAN_USE_NAMECHEAP = False
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Check to make sure requests and xml are installed and requests
'''
if CAN_USE_NAMECHEAP:
return 'namecheap_ssl'
return False
def reissue(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Reissues a purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/reissue.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.reissue my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.reissue', "SSLReissueResult", csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def activate(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Activates a newly-purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/activate.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.activate my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.activate', 'SSLActivateResult', csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def __get_certificates(command,
result_tag_name,
csr_file,
certificate_id,
web_server_type,
approver_email,
http_dc_validation,
kwargs):
web_server_types = ('apacheopenssl',
'apachessl',
'apacheraven',
'apachessleay',
'c2net',
'ibmhttp',
'iplanet',
'domino',
'dominogo4625',
'dominogo4626',
'netscape',
'zeusv3',
'apache2',
'apacheapachessl',
'cobaltseries',
'cpanel',
'ensim',
'hsphere',
'ipswitch',
'plesk',
'tomcat',
'weblogic',
'website',
'webstar',
'iis',
'other',
'iis4',
'iis5',
)
if web_server_type not in web_server_types:
log.error('Invalid option for web_server_type=%s', web_server_type)
raise Exception('Invalid option for web_server_type=' + web_server_type)
if approver_email is not None and http_dc_validation:
log.error('approver_email and http_dc_validation cannot both have values')
raise Exception('approver_email and http_dc_validation cannot both have values')
if approver_email is None and not http_dc_validation:
log.error('approver_email or http_dc_validation must have a value')
raise Exception('approver_email or http_dc_validation must have a value')
opts = salt.utils.namecheap.get_opts(command)
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateID'] = certificate_id
opts['WebServerType'] = web_server_type
if approver_email is not None:
opts['ApproverEmail'] = approver_email
if http_dc_validation:
opts['HTTPDCValidation'] = 'True'
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslresult = response_xml.getElementsByTagName(result_tag_name)[0]
result = salt.utils.namecheap.atts_to_dict(sslresult)
if http_dc_validation:
validation_tag = sslresult.getElementsByTagName('HttpDCValidation')
if validation_tag:
validation_tag = validation_tag[0]
if validation_tag.getAttribute('ValueAvailable').lower() == 'true':
validation_dict = {'filename': validation_tag.getElementsByTagName('FileName')[0].childNodes[0].data,
'filecontent': validation_tag.getElementsByTagName('FileContent')[0].childNodes[
0].data}
result['httpdcvalidation'] = validation_dict
return result
def renew(years, certificate_id, certificate_type, promotion_code=None):
'''
Renews an SSL certificate if it is ACTIVE and Expires <= 30 days. Returns
the following information:
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
years : 1
Number of years to register
certificate_id
Unique ID of the SSL certificate you wish to renew
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when renewing the certificate
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.renew 1 my-cert-id RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.renew')
opts['Years'] = six.text_type(years)
opts['CertificateID'] = six.text_type(certificate_id)
opts['SSLType'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslrenewresult = response_xml.getElementsByTagName('SSLRenewResult')[0]
return salt.utils.namecheap.atts_to_dict(sslrenewresult)
def create(years, certificate_type, promotion_code=None, sans_to_add=None):
'''
Creates a new SSL certificate. Returns the following information:
- Whether or not the SSL order was successful
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
- The date on which the certificate was created
- The date on which the certificate will expire
- The type of SSL certificate
- The number of years for which the certificate was purchased
- The current status of the SSL certificate
years : 1
Number of years to register
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when creating the certificate
sans_to_add : 0
This parameter defines the number of add-on domains to be purchased in
addition to the default number of domains included with a multi-domain
certificate. Each certificate that supports SANs has the default number
of domains included. You may check the default number of domains
included and the maximum number of domains that can be added to it in
the table below.
+----------+----------------+----------------------+-------------------+----------------+
| Provider | Product name | Default number of | Maximum number of | Maximum number |
| | | domains (domain from | total domains | of domains |
| | | CSR is counted here) | | that can be |
| | | | | passed in |
| | | | | sans_to_add |
| | | | | parameter |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | PositiveSSL | 3 | 100 | 97 |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Multi-Domain | 3 | 100 | 97 |
| | SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | EV Multi- | 3 | 100 | 97 |
| | Domain SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Unified | 3 | 100 | 97 |
| | Communications | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | QuickSSL | 1 | 1 domain + | The only |
| | Premium | | 4 subdomains | supported |
| | | | | value is 4 |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True | 5 | 25 | 20 |
| | BusinessID | | | |
| | with EV | | | |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True Business | 5 | 25 | 20 |
| | ID Multi- | | | |
| | Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server with | | | |
| | EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SGC Supercerts | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro | | | |
+----------+----------------+----------------------+-------------------+----------------+
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.create 2 RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.create')
opts['Years'] = years
opts['Type'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
if sans_to_add is not None:
opts['SANStoADD'] = sans_to_add
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslcreateresult = response_xml.getElementsByTagName('SSLCreateResult')[0]
sslcertinfo = sslcreateresult.getElementsByTagName('SSLCertificate')[0]
result = salt.utils.namecheap.atts_to_dict(sslcreateresult)
result.update(salt.utils.namecheap.atts_to_dict(sslcertinfo))
return result
def get_list(**kwargs):
'''
Returns a list of SSL certificates for a particular user
ListType : All
Possible values:
- All
- Processing
- EmailSent
- TechnicalProblem
- InProgress
- Completed
- Deactivated
- Active
- Cancelled
- NewPurchase
- NewRenewal
SearchTerm
Keyword to look for on the SSL list
Page : 1
Page number to return
PageSize : 20
Total number of SSL certificates to display per page (minimum:
``10``, maximum: ``100``)
SoryBy
One of ``PURCHASEDATE``, ``PURCHASEDATE_DESC``, ``SSLTYPE``,
``SSLTYPE_DESC``, ``EXPIREDATETIME``, ``EXPIREDATETIME_DESC``,
``Host_Name``, or ``Host_Name_DESC``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_list Processing
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getList')
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return []
ssllistresult = response_xml.getElementsByTagName('SSLListResult')[0]
result = []
for e in ssllistresult.getElementsByTagName('SSL'):
ssl = salt.utils.namecheap.atts_to_dict(e)
result.append(ssl)
return result
def get_info(certificate_id, returncertificate=False, returntype=None):
'''
Retrieves information about the requested SSL certificate. Returns a
dictionary of information about the SSL certificate with two keys:
- **ssl** - Contains the metadata information
- **certificate** - Contains the details for the certificate such as the
CSR, Approver, and certificate data
certificate_id
Unique ID of the SSL certificate
returncertificate : False
Set to ``True`` to ask for the certificate in response
returntype
Optional type for the returned certificate. Can be either "Individual"
(for X.509 format) or "PKCS7"
.. note::
Required if ``returncertificate`` is ``True``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_info my-cert-id
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getinfo')
opts['certificateID'] = certificate_id
if returncertificate:
opts['returncertificate'] = "true"
if returntype is None:
log.error('returntype must be specified when returncertificate is set to True')
raise Exception('returntype must be specified when returncertificate is set to True')
if returntype not in ["Individual", "PKCS7"]:
log.error('returntype must be specified as Individual or PKCS7, not %s', returntype)
raise Exception('returntype must be specified as Individual or PKCS7, not ' + returntype)
opts['returntype'] = returntype
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return {}
sslinforesult = response_xml.getElementsByTagName('SSLGetInfoResult')[0]
return salt.utils.namecheap.xml_to_dict(sslinforesult)
|
saltstack/salt
|
salt/modules/namecheap_ssl.py
|
get_list
|
python
|
def get_list(**kwargs):
'''
Returns a list of SSL certificates for a particular user
ListType : All
Possible values:
- All
- Processing
- EmailSent
- TechnicalProblem
- InProgress
- Completed
- Deactivated
- Active
- Cancelled
- NewPurchase
- NewRenewal
SearchTerm
Keyword to look for on the SSL list
Page : 1
Page number to return
PageSize : 20
Total number of SSL certificates to display per page (minimum:
``10``, maximum: ``100``)
SoryBy
One of ``PURCHASEDATE``, ``PURCHASEDATE_DESC``, ``SSLTYPE``,
``SSLTYPE_DESC``, ``EXPIREDATETIME``, ``EXPIREDATETIME_DESC``,
``Host_Name``, or ``Host_Name_DESC``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_list Processing
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getList')
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return []
ssllistresult = response_xml.getElementsByTagName('SSLListResult')[0]
result = []
for e in ssllistresult.getElementsByTagName('SSL'):
ssl = salt.utils.namecheap.atts_to_dict(e)
result.append(ssl)
return result
|
Returns a list of SSL certificates for a particular user
ListType : All
Possible values:
- All
- Processing
- EmailSent
- TechnicalProblem
- InProgress
- Completed
- Deactivated
- Active
- Cancelled
- NewPurchase
- NewRenewal
SearchTerm
Keyword to look for on the SSL list
Page : 1
Page number to return
PageSize : 20
Total number of SSL certificates to display per page (minimum:
``10``, maximum: ``100``)
SoryBy
One of ``PURCHASEDATE``, ``PURCHASEDATE_DESC``, ``SSLTYPE``,
``SSLTYPE_DESC``, ``EXPIREDATETIME``, ``EXPIREDATETIME_DESC``,
``Host_Name``, or ``Host_Name_DESC``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_list Processing
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_ssl.py#L699-L755
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n",
"def get_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.get(namecheap_url, params=opts, timeout=45))\n",
"def atts_to_dict(xml):\n result = {}\n if xml.attributes is not None:\n for key, value in xml.attributes.items():\n result[key.lower()] = string_to_value(value)\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
Namecheap SSL Certificate Management
.. versionadded:: 2017.7.0
Prerequisites
-------------
This module uses the ``requests`` Python module to communicate to the namecheap
API.
Configuration
-------------
The Namecheap username, API key and URL should be set in the minion configuration
file, or in the Pillar data.
.. code-block:: yaml
namecheap.name: companyname
namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3
namecheap.client_ip: 162.155.30.172
#Real url
namecheap.url: https://api.namecheap.com/xml.response
#Sandbox url
#namecheap.url: https://api.sandbox.namecheap.xml.response
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.files
import salt.utils.stringutils
try:
import salt.utils.namecheap
CAN_USE_NAMECHEAP = True
except ImportError:
CAN_USE_NAMECHEAP = False
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Check to make sure requests and xml are installed and requests
'''
if CAN_USE_NAMECHEAP:
return 'namecheap_ssl'
return False
def reissue(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Reissues a purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/reissue.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.reissue my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.reissue', "SSLReissueResult", csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def activate(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Activates a newly-purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/activate.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.activate my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.activate', 'SSLActivateResult', csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def __get_certificates(command,
result_tag_name,
csr_file,
certificate_id,
web_server_type,
approver_email,
http_dc_validation,
kwargs):
web_server_types = ('apacheopenssl',
'apachessl',
'apacheraven',
'apachessleay',
'c2net',
'ibmhttp',
'iplanet',
'domino',
'dominogo4625',
'dominogo4626',
'netscape',
'zeusv3',
'apache2',
'apacheapachessl',
'cobaltseries',
'cpanel',
'ensim',
'hsphere',
'ipswitch',
'plesk',
'tomcat',
'weblogic',
'website',
'webstar',
'iis',
'other',
'iis4',
'iis5',
)
if web_server_type not in web_server_types:
log.error('Invalid option for web_server_type=%s', web_server_type)
raise Exception('Invalid option for web_server_type=' + web_server_type)
if approver_email is not None and http_dc_validation:
log.error('approver_email and http_dc_validation cannot both have values')
raise Exception('approver_email and http_dc_validation cannot both have values')
if approver_email is None and not http_dc_validation:
log.error('approver_email or http_dc_validation must have a value')
raise Exception('approver_email or http_dc_validation must have a value')
opts = salt.utils.namecheap.get_opts(command)
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateID'] = certificate_id
opts['WebServerType'] = web_server_type
if approver_email is not None:
opts['ApproverEmail'] = approver_email
if http_dc_validation:
opts['HTTPDCValidation'] = 'True'
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslresult = response_xml.getElementsByTagName(result_tag_name)[0]
result = salt.utils.namecheap.atts_to_dict(sslresult)
if http_dc_validation:
validation_tag = sslresult.getElementsByTagName('HttpDCValidation')
if validation_tag:
validation_tag = validation_tag[0]
if validation_tag.getAttribute('ValueAvailable').lower() == 'true':
validation_dict = {'filename': validation_tag.getElementsByTagName('FileName')[0].childNodes[0].data,
'filecontent': validation_tag.getElementsByTagName('FileContent')[0].childNodes[
0].data}
result['httpdcvalidation'] = validation_dict
return result
def renew(years, certificate_id, certificate_type, promotion_code=None):
'''
Renews an SSL certificate if it is ACTIVE and Expires <= 30 days. Returns
the following information:
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
years : 1
Number of years to register
certificate_id
Unique ID of the SSL certificate you wish to renew
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when renewing the certificate
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.renew 1 my-cert-id RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.renew')
opts['Years'] = six.text_type(years)
opts['CertificateID'] = six.text_type(certificate_id)
opts['SSLType'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslrenewresult = response_xml.getElementsByTagName('SSLRenewResult')[0]
return salt.utils.namecheap.atts_to_dict(sslrenewresult)
def create(years, certificate_type, promotion_code=None, sans_to_add=None):
'''
Creates a new SSL certificate. Returns the following information:
- Whether or not the SSL order was successful
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
- The date on which the certificate was created
- The date on which the certificate will expire
- The type of SSL certificate
- The number of years for which the certificate was purchased
- The current status of the SSL certificate
years : 1
Number of years to register
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when creating the certificate
sans_to_add : 0
This parameter defines the number of add-on domains to be purchased in
addition to the default number of domains included with a multi-domain
certificate. Each certificate that supports SANs has the default number
of domains included. You may check the default number of domains
included and the maximum number of domains that can be added to it in
the table below.
+----------+----------------+----------------------+-------------------+----------------+
| Provider | Product name | Default number of | Maximum number of | Maximum number |
| | | domains (domain from | total domains | of domains |
| | | CSR is counted here) | | that can be |
| | | | | passed in |
| | | | | sans_to_add |
| | | | | parameter |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | PositiveSSL | 3 | 100 | 97 |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Multi-Domain | 3 | 100 | 97 |
| | SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | EV Multi- | 3 | 100 | 97 |
| | Domain SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Unified | 3 | 100 | 97 |
| | Communications | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | QuickSSL | 1 | 1 domain + | The only |
| | Premium | | 4 subdomains | supported |
| | | | | value is 4 |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True | 5 | 25 | 20 |
| | BusinessID | | | |
| | with EV | | | |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True Business | 5 | 25 | 20 |
| | ID Multi- | | | |
| | Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server with | | | |
| | EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SGC Supercerts | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro | | | |
+----------+----------------+----------------------+-------------------+----------------+
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.create 2 RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.create')
opts['Years'] = years
opts['Type'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
if sans_to_add is not None:
opts['SANStoADD'] = sans_to_add
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslcreateresult = response_xml.getElementsByTagName('SSLCreateResult')[0]
sslcertinfo = sslcreateresult.getElementsByTagName('SSLCertificate')[0]
result = salt.utils.namecheap.atts_to_dict(sslcreateresult)
result.update(salt.utils.namecheap.atts_to_dict(sslcertinfo))
return result
def parse_csr(csr_file, certificate_type, http_dc_validation=False):
'''
Parses the CSR. Returns a dictionary of result values.
csr_file
Path to Certificate Signing Request file
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
http_dc_validation : False
Set to ``True`` if a Comodo certificate and validation should be
done with files instead of emails and to return the info to do so
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.parse_csr my-csr-file PremiumSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
opts = salt.utils.namecheap.get_opts('namecheap.ssl.parseCSR')
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateType'] = certificate_type
if http_dc_validation:
opts['HTTPDCValidation'] = 'true'
response_xml = salt.utils.namecheap.post_request(opts)
sslparseresult = response_xml.getElementsByTagName('SSLParseCSRResult')[0]
return salt.utils.namecheap.xml_to_dict(sslparseresult)
def get_info(certificate_id, returncertificate=False, returntype=None):
'''
Retrieves information about the requested SSL certificate. Returns a
dictionary of information about the SSL certificate with two keys:
- **ssl** - Contains the metadata information
- **certificate** - Contains the details for the certificate such as the
CSR, Approver, and certificate data
certificate_id
Unique ID of the SSL certificate
returncertificate : False
Set to ``True`` to ask for the certificate in response
returntype
Optional type for the returned certificate. Can be either "Individual"
(for X.509 format) or "PKCS7"
.. note::
Required if ``returncertificate`` is ``True``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_info my-cert-id
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getinfo')
opts['certificateID'] = certificate_id
if returncertificate:
opts['returncertificate'] = "true"
if returntype is None:
log.error('returntype must be specified when returncertificate is set to True')
raise Exception('returntype must be specified when returncertificate is set to True')
if returntype not in ["Individual", "PKCS7"]:
log.error('returntype must be specified as Individual or PKCS7, not %s', returntype)
raise Exception('returntype must be specified as Individual or PKCS7, not ' + returntype)
opts['returntype'] = returntype
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return {}
sslinforesult = response_xml.getElementsByTagName('SSLGetInfoResult')[0]
return salt.utils.namecheap.xml_to_dict(sslinforesult)
|
saltstack/salt
|
salt/modules/namecheap_ssl.py
|
get_info
|
python
|
def get_info(certificate_id, returncertificate=False, returntype=None):
'''
Retrieves information about the requested SSL certificate. Returns a
dictionary of information about the SSL certificate with two keys:
- **ssl** - Contains the metadata information
- **certificate** - Contains the details for the certificate such as the
CSR, Approver, and certificate data
certificate_id
Unique ID of the SSL certificate
returncertificate : False
Set to ``True`` to ask for the certificate in response
returntype
Optional type for the returned certificate. Can be either "Individual"
(for X.509 format) or "PKCS7"
.. note::
Required if ``returncertificate`` is ``True``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_info my-cert-id
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getinfo')
opts['certificateID'] = certificate_id
if returncertificate:
opts['returncertificate'] = "true"
if returntype is None:
log.error('returntype must be specified when returncertificate is set to True')
raise Exception('returntype must be specified when returncertificate is set to True')
if returntype not in ["Individual", "PKCS7"]:
log.error('returntype must be specified as Individual or PKCS7, not %s', returntype)
raise Exception('returntype must be specified as Individual or PKCS7, not ' + returntype)
opts['returntype'] = returntype
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return {}
sslinforesult = response_xml.getElementsByTagName('SSLGetInfoResult')[0]
return salt.utils.namecheap.xml_to_dict(sslinforesult)
|
Retrieves information about the requested SSL certificate. Returns a
dictionary of information about the SSL certificate with two keys:
- **ssl** - Contains the metadata information
- **certificate** - Contains the details for the certificate such as the
CSR, Approver, and certificate data
certificate_id
Unique ID of the SSL certificate
returncertificate : False
Set to ``True`` to ask for the certificate in response
returntype
Optional type for the returned certificate. Can be either "Individual"
(for X.509 format) or "PKCS7"
.. note::
Required if ``returncertificate`` is ``True``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_info my-cert-id
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_ssl.py#L758-L806
|
[
"def get_opts(command):\n opts = {}\n opts['ApiUser'] = __salt__['config.option']('namecheap.name')\n opts['UserName'] = __salt__['config.option']('namecheap.user')\n opts['ApiKey'] = __salt__['config.option']('namecheap.key')\n opts['ClientIp'] = __salt__['config.option']('namecheap.client_ip')\n opts['Command'] = command\n return opts\n",
"def get_request(opts):\n namecheap_url = __salt__['config.option']('namecheap.url')\n return _handle_request(requests.get(namecheap_url, params=opts, timeout=45))\n",
"def xml_to_dict(xml):\n if xml.nodeType == xml.CDATA_SECTION_NODE:\n return xml.data\n result = atts_to_dict(xml)\n if not [n for n in xml.childNodes if n.nodeType != xml.TEXT_NODE]:\n if result > 0:\n if xml.firstChild is not None and xml.firstChild.data:\n result['data'] = xml.firstChild.data\n elif xml.firstChild is not None and xml.firstChild.data:\n return xml.firstChild.data\n else:\n return None\n elif xml.childNodes.length == 1 and \\\n xml.childNodes[0].nodeType == xml.CDATA_SECTION_NODE:\n return xml.childNodes[0].data\n else:\n for n in xml.childNodes:\n if n.nodeType == xml.CDATA_SECTION_NODE:\n\n if xml.tagName.lower() in result:\n val = result[xml.tagName.lower()]\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(n.data)\n result[xml.tagName.lower()] = val\n else:\n result[xml.tagName.lower()] = n.data\n\n elif n.nodeType != xml.TEXT_NODE:\n\n if n.tagName.lower() in result:\n val = result[n.tagName.lower()]\n\n if not isinstance(val, list):\n temp = [val]\n val = temp\n val.append(xml_to_dict(n))\n result[n.tagName.lower()] = val\n else:\n result[n.tagName.lower()] = xml_to_dict(n)\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
Namecheap SSL Certificate Management
.. versionadded:: 2017.7.0
Prerequisites
-------------
This module uses the ``requests`` Python module to communicate to the namecheap
API.
Configuration
-------------
The Namecheap username, API key and URL should be set in the minion configuration
file, or in the Pillar data.
.. code-block:: yaml
namecheap.name: companyname
namecheap.key: a1b2c3d4e5f67a8b9c0d1e2f3
namecheap.client_ip: 162.155.30.172
#Real url
namecheap.url: https://api.namecheap.com/xml.response
#Sandbox url
#namecheap.url: https://api.sandbox.namecheap.xml.response
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.files
import salt.utils.stringutils
try:
import salt.utils.namecheap
CAN_USE_NAMECHEAP = True
except ImportError:
CAN_USE_NAMECHEAP = False
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Check to make sure requests and xml are installed and requests
'''
if CAN_USE_NAMECHEAP:
return 'namecheap_ssl'
return False
def reissue(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Reissues a purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/reissue.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.reissue my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.reissue', "SSLReissueResult", csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def activate(csr_file,
certificate_id,
web_server_type,
approver_email=None,
http_dc_validation=False,
**kwargs):
'''
Activates a newly-purchased SSL certificate. Returns a dictionary of result
values.
csr_file
Path to Certificate Signing Request file
certificate_id
Unique ID of the SSL certificate you wish to activate
web_server_type
The type of certificate format to return. Possible values include:
- apache2
- apacheapachessl
- apacheopenssl
- apacheraven
- apachessl
- apachessleay
- c2net
- cobaltseries
- cpanel
- domino
- dominogo4625
- dominogo4626
- ensim
- hsphere
- ibmhttp
- iis
- iis4
- iis5
- iplanet
- ipswitch
- netscape
- other
- plesk
- tomcat
- weblogic
- website
- webstar
- zeusv3
approver_email
The email ID which is on the approver email list.
.. note::
``http_dc_validation`` must be set to ``False`` if this option is
used.
http_dc_validation : False
Whether or not to activate using HTTP-based validation.
.. note::
For other parameters which may be required, see here__.
.. __: https://www.namecheap.com/support/api/methods/ssl/activate.aspx
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.activate my-csr-file my-cert-id apachessl
'''
return __get_certificates('namecheap.ssl.activate', 'SSLActivateResult', csr_file, certificate_id, web_server_type,
approver_email, http_dc_validation, kwargs)
def __get_certificates(command,
result_tag_name,
csr_file,
certificate_id,
web_server_type,
approver_email,
http_dc_validation,
kwargs):
web_server_types = ('apacheopenssl',
'apachessl',
'apacheraven',
'apachessleay',
'c2net',
'ibmhttp',
'iplanet',
'domino',
'dominogo4625',
'dominogo4626',
'netscape',
'zeusv3',
'apache2',
'apacheapachessl',
'cobaltseries',
'cpanel',
'ensim',
'hsphere',
'ipswitch',
'plesk',
'tomcat',
'weblogic',
'website',
'webstar',
'iis',
'other',
'iis4',
'iis5',
)
if web_server_type not in web_server_types:
log.error('Invalid option for web_server_type=%s', web_server_type)
raise Exception('Invalid option for web_server_type=' + web_server_type)
if approver_email is not None and http_dc_validation:
log.error('approver_email and http_dc_validation cannot both have values')
raise Exception('approver_email and http_dc_validation cannot both have values')
if approver_email is None and not http_dc_validation:
log.error('approver_email or http_dc_validation must have a value')
raise Exception('approver_email or http_dc_validation must have a value')
opts = salt.utils.namecheap.get_opts(command)
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateID'] = certificate_id
opts['WebServerType'] = web_server_type
if approver_email is not None:
opts['ApproverEmail'] = approver_email
if http_dc_validation:
opts['HTTPDCValidation'] = 'True'
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslresult = response_xml.getElementsByTagName(result_tag_name)[0]
result = salt.utils.namecheap.atts_to_dict(sslresult)
if http_dc_validation:
validation_tag = sslresult.getElementsByTagName('HttpDCValidation')
if validation_tag:
validation_tag = validation_tag[0]
if validation_tag.getAttribute('ValueAvailable').lower() == 'true':
validation_dict = {'filename': validation_tag.getElementsByTagName('FileName')[0].childNodes[0].data,
'filecontent': validation_tag.getElementsByTagName('FileContent')[0].childNodes[
0].data}
result['httpdcvalidation'] = validation_dict
return result
def renew(years, certificate_id, certificate_type, promotion_code=None):
'''
Renews an SSL certificate if it is ACTIVE and Expires <= 30 days. Returns
the following information:
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
years : 1
Number of years to register
certificate_id
Unique ID of the SSL certificate you wish to renew
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when renewing the certificate
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.renew 1 my-cert-id RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.renew')
opts['Years'] = six.text_type(years)
opts['CertificateID'] = six.text_type(certificate_id)
opts['SSLType'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslrenewresult = response_xml.getElementsByTagName('SSLRenewResult')[0]
return salt.utils.namecheap.atts_to_dict(sslrenewresult)
def create(years, certificate_type, promotion_code=None, sans_to_add=None):
'''
Creates a new SSL certificate. Returns the following information:
- Whether or not the SSL order was successful
- The certificate ID
- The order ID
- The transaction ID
- The amount charged for the order
- The date on which the certificate was created
- The date on which the certificate will expire
- The type of SSL certificate
- The number of years for which the certificate was purchased
- The current status of the SSL certificate
years : 1
Number of years to register
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
promotional_code
An optional promo code to use when creating the certificate
sans_to_add : 0
This parameter defines the number of add-on domains to be purchased in
addition to the default number of domains included with a multi-domain
certificate. Each certificate that supports SANs has the default number
of domains included. You may check the default number of domains
included and the maximum number of domains that can be added to it in
the table below.
+----------+----------------+----------------------+-------------------+----------------+
| Provider | Product name | Default number of | Maximum number of | Maximum number |
| | | domains (domain from | total domains | of domains |
| | | CSR is counted here) | | that can be |
| | | | | passed in |
| | | | | sans_to_add |
| | | | | parameter |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | PositiveSSL | 3 | 100 | 97 |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Multi-Domain | 3 | 100 | 97 |
| | SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | EV Multi- | 3 | 100 | 97 |
| | Domain SSL | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Comodo | Unified | 3 | 100 | 97 |
| | Communications | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | QuickSSL | 1 | 1 domain + | The only |
| | Premium | | 4 subdomains | supported |
| | | | | value is 4 |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True | 5 | 25 | 20 |
| | BusinessID | | | |
| | with EV | | | |
| | Multi-Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| GeoTrust | True Business | 5 | 25 | 20 |
| | ID Multi- | | | |
| | Domain | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SSL Web | 1 | 25 | 24 |
| | Server with | | | |
| | EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Thawte | SGC Supercerts | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | with EV | | | |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
+----------+----------------+----------------------+-------------------+----------------+
| Symantec | Secure Site | 1 | 25 | 24 |
| | Pro | | | |
+----------+----------------+----------------------+-------------------+----------------+
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.create 2 RapidSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
if years < 1 or years > 5:
log.error('Invalid option for years=%s', years)
raise Exception('Invalid option for years=' + six.text_type(years))
opts = salt.utils.namecheap.get_opts('namecheap.ssl.create')
opts['Years'] = years
opts['Type'] = certificate_type
if promotion_code is not None:
opts['PromotionCode'] = promotion_code
if sans_to_add is not None:
opts['SANStoADD'] = sans_to_add
response_xml = salt.utils.namecheap.post_request(opts)
if response_xml is None:
return {}
sslcreateresult = response_xml.getElementsByTagName('SSLCreateResult')[0]
sslcertinfo = sslcreateresult.getElementsByTagName('SSLCertificate')[0]
result = salt.utils.namecheap.atts_to_dict(sslcreateresult)
result.update(salt.utils.namecheap.atts_to_dict(sslcertinfo))
return result
def parse_csr(csr_file, certificate_type, http_dc_validation=False):
'''
Parses the CSR. Returns a dictionary of result values.
csr_file
Path to Certificate Signing Request file
certificate_type
Type of SSL Certificate. Possible values include:
- EV Multi Domain SSL
- EV SSL
- EV SSL SGC
- EssentialSSL
- EssentialSSL Wildcard
- InstantSSL
- InstantSSL Pro
- Multi Domain SSL
- PositiveSSL
- PositiveSSL Multi Domain
- PositiveSSL Wildcard
- PremiumSSL
- PremiumSSL Wildcard
- QuickSSL Premium
- RapidSSL
- RapidSSL Wildcard
- SGC Supercert
- SSL Web Server
- SSL Webserver EV
- SSL123
- Secure Site
- Secure Site Pro
- Secure Site Pro with EV
- Secure Site with EV
- True BusinessID
- True BusinessID Multi Domain
- True BusinessID Wildcard
- True BusinessID with EV
- True BusinessID with EV Multi Domain
- Unified Communications
http_dc_validation : False
Set to ``True`` if a Comodo certificate and validation should be
done with files instead of emails and to return the info to do so
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.parse_csr my-csr-file PremiumSSL
'''
valid_certs = ('QuickSSL Premium',
'RapidSSL',
'RapidSSL Wildcard',
'PremiumSSL',
'InstantSSL',
'PositiveSSL',
'PositiveSSL Wildcard',
'True BusinessID with EV',
'True BusinessID',
'True BusinessID Wildcard',
'True BusinessID Multi Domain',
'True BusinessID with EV Multi Domain',
'Secure Site',
'Secure Site Pro',
'Secure Site with EV',
'Secure Site Pro with EV',
'EssentialSSL',
'EssentialSSL Wildcard',
'InstantSSL Pro',
'PremiumSSL Wildcard',
'EV SSL',
'EV SSL SGC',
'SSL123',
'SSL Web Server',
'SGC Supercert',
'SSL Webserver EV',
'EV Multi Domain SSL',
'Multi Domain SSL',
'PositiveSSL Multi Domain',
'Unified Communications',
)
if certificate_type not in valid_certs:
log.error('Invalid option for certificate_type=%s', certificate_type)
raise Exception('Invalid option for certificate_type=' + certificate_type)
opts = salt.utils.namecheap.get_opts('namecheap.ssl.parseCSR')
with salt.utils.files.fopen(csr_file, 'rb') as csr_handle:
opts['csr'] = salt.utils.stringutils.to_unicode(
csr_handle.read()
)
opts['CertificateType'] = certificate_type
if http_dc_validation:
opts['HTTPDCValidation'] = 'true'
response_xml = salt.utils.namecheap.post_request(opts)
sslparseresult = response_xml.getElementsByTagName('SSLParseCSRResult')[0]
return salt.utils.namecheap.xml_to_dict(sslparseresult)
def get_list(**kwargs):
'''
Returns a list of SSL certificates for a particular user
ListType : All
Possible values:
- All
- Processing
- EmailSent
- TechnicalProblem
- InProgress
- Completed
- Deactivated
- Active
- Cancelled
- NewPurchase
- NewRenewal
SearchTerm
Keyword to look for on the SSL list
Page : 1
Page number to return
PageSize : 20
Total number of SSL certificates to display per page (minimum:
``10``, maximum: ``100``)
SoryBy
One of ``PURCHASEDATE``, ``PURCHASEDATE_DESC``, ``SSLTYPE``,
``SSLTYPE_DESC``, ``EXPIREDATETIME``, ``EXPIREDATETIME_DESC``,
``Host_Name``, or ``Host_Name_DESC``
CLI Example:
.. code-block:: bash
salt 'my-minion' namecheap_ssl.get_list Processing
'''
opts = salt.utils.namecheap.get_opts('namecheap.ssl.getList')
for key, value in six.iteritems(kwargs):
opts[key] = value
response_xml = salt.utils.namecheap.get_request(opts)
if response_xml is None:
return []
ssllistresult = response_xml.getElementsByTagName('SSLListResult')[0]
result = []
for e in ssllistresult.getElementsByTagName('SSL'):
ssl = salt.utils.namecheap.atts_to_dict(e)
result.append(ssl)
return result
|
saltstack/salt
|
salt/states/cron.py
|
_check_cron
|
python
|
def _check_cron(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
comment=None,
commented=None,
identifier=None,
special=None):
'''
Return the changes
'''
if minute is not None:
minute = six.text_type(minute).lower()
if hour is not None:
hour = six.text_type(hour).lower()
if daymonth is not None:
daymonth = six.text_type(daymonth).lower()
if month is not None:
month = six.text_type(month).lower()
if dayweek is not None:
dayweek = six.text_type(dayweek).lower()
if identifier is not None:
identifier = six.text_type(identifier)
if commented is not None:
commented = commented is True
if cmd is not None:
cmd = six.text_type(cmd)
lst = __salt__['cron.list_tab'](user)
if special is None:
for cron in lst['crons']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['minute'], minute), (cron['hour'], hour),
(cron['daymonth'], daymonth), (cron['month'], month),
(cron['dayweek'], dayweek), (cron['identifier'], identifier),
(cron['cmd'], cmd), (cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
else:
for cron in lst['special']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['spec'], special),
(cron['identifier'], identifier),
(cron['cmd'], cmd),
(cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
return 'absent'
|
Return the changes
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L161-L214
|
[
"def _cron_matched(cron, cmd, identifier=None):\n '''Check if:\n - we find a cron with same cmd, old state behavior\n - but also be smart enough to remove states changed crons where we do\n not removed priorly by a cron.absent by matching on the provided\n identifier.\n We assure retrocompatibility by only checking on identifier if\n and only if an identifier was set on the serialized crontab\n '''\n ret, id_matched = False, None\n cid = _cron_id(cron)\n if cid:\n if not identifier:\n identifier = SALT_CRON_NO_IDENTIFIER\n eidentifier = _ensure_string(identifier)\n # old style second round\n # after saving crontab, we must check that if\n # we have not the same command, but the default id\n # to not set that as a match\n if (\n cron.get('cmd', None) != cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and eidentifier == SALT_CRON_NO_IDENTIFIER\n ):\n id_matched = False\n else:\n # on saving, be sure not to overwrite a cron\n # with specific identifier but also track\n # crons where command is the same\n # but with the default if that we gonna overwrite\n if (\n cron.get('cmd', None) == cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and identifier\n ):\n cid = eidentifier\n id_matched = eidentifier == cid\n if (\n ((id_matched is None) and cmd == cron.get('cmd', None))\n or id_matched\n ):\n ret = True\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Management of cron, the Unix command scheduler
==============================================
Cron declarations require a number of parameters. The following are the
parameters used by Salt to define the various timing values for a cron job:
* ``minute``
* ``hour``
* ``daymonth``
* ``month``
* ``dayweek`` (0 to 6 are Sunday through Saturday, 7 can also be used for
Sunday)
.. warning::
Any timing arguments not specified take a value of ``*``. This means that
setting ``hour`` to ``5``, while not defining the ``minute`` param, will
result in Salt adding a job that will execute every minute between 5 and 6
A.M.!
Additionally, the default user for these states is ``root``. Therefore, if
the cron job is for another user, it is necessary to specify that user with
the ``user`` parameter.
A long time ago (before 2014.2), when making changes to an existing cron job,
the name declaration is the parameter used to uniquely identify the job,
so if an existing cron that looks like this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 5
Is changed to this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 7
- hour: 2
Then the existing cron will be updated, but if the cron command is changed,
then a new cron job will be added to the user's crontab.
The current behavior is still relying on that mechanism, but you can also
specify an identifier to identify your crontabs:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 7
- hour: 2
.. versionadded:: 2014.1.2
And, some months later, you modify it:
.. code-block:: yaml
superscript > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 3
- hour: 4
.. versionadded:: 2014.1.2
The old **date > /tmp/crontest** will be replaced by
**superscript > /tmp/crontest**.
Additionally, Salt also supports running a cron every ``x minutes`` very similarly to the Unix
convention of using ``*/5`` to have a job run every five minutes. In Salt, this
looks like:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: '*/5'
The job will now run every 5 minutes.
Additionally, the temporal parameters (minute, hour, etc.) can be randomized by
using ``random`` instead of using a specific value. For example, by using the
``random`` keyword in the ``minute`` parameter of a cron state, the same cron
job can be pushed to hundreds or thousands of hosts, and they would each use a
randomly-generated minute. This can be helpful when the cron job accesses a
network resource, and it is not desirable for all hosts to run the job
concurrently.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- minute: random
- hour: 2
.. versionadded:: 0.16.0
Since Salt assumes a value of ``*`` for unspecified temporal parameters, adding
a parameter to the state and setting it to ``random`` will change that value
from ``*`` to a randomized numeric value. However, if that field in the cron
entry on the minion already contains a numeric value, then using the ``random``
keyword will not modify it.
Added the opportunity to set a job with a special keyword like '@reboot' or
'@hourly'. Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- special: '@hourly'
The script will be executed every reboot if cron daemon support this option.
.. code-block:: yaml
/path/to/cron/otherscript:
cron.absent:
- user: root
- special: '@daily'
This counter part definition will ensure than a job with a special keyword
is not set.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
# Import salt libs
import salt.utils.files
from salt.modules.cron import (
_needs_change,
_cron_matched
)
from salt.ext import six
def __virtual__():
if 'cron.list_tab' in __salt__:
return True
else:
return (False, 'cron module could not be loaded')
def _check_cron_env(user,
name,
value=None):
'''
Return the environment changes
'''
if value is None:
value = "" # Matching value set in salt.modules.cron._render_tab
lst = __salt__['cron.list_tab'](user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
return 'update'
return 'present'
return 'absent'
def _get_cron_info():
'''
Returns the proper group owner and path to the cron directory
'''
owner = 'root'
if __grains__['os'] == 'FreeBSD':
group = 'wheel'
crontab_dir = '/var/cron/tabs'
elif __grains__['os'] == 'OpenBSD':
group = 'crontab'
crontab_dir = '/var/cron/tabs'
elif __grains__['os_family'] == 'Solaris':
group = 'root'
crontab_dir = '/var/spool/cron/crontabs'
elif __grains__['os'] == 'MacOS':
group = 'wheel'
crontab_dir = '/usr/lib/cron/tabs'
else:
group = 'root'
crontab_dir = '/var/spool/cron'
return owner, group, crontab_dir
def present(name,
user='root',
minute='*',
hour='*',
daymonth='*',
month='*',
dayweek='*',
comment=None,
commented=False,
identifier=False,
special=None):
'''
Verifies that the specified cron job is present for the specified user.
It is recommended to use `identifier`. Otherwise the cron job is installed
twice if you change the name.
For more advanced information about what exactly can be set in the cron
timing parameters, check your cron system's documentation. Most Unix-like
systems' cron documentation can be found via the crontab man page:
``man 5 crontab``.
name
The command that should be executed by the cron job.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
minute
The information to be set into the minute section, this can be any
string supported by your cron system's the minute field. Default is
``*``
hour
The information to be set in the hour section. Default is ``*``
daymonth
The information to be set in the day of month section. Default is ``*``
month
The information to be set in the month section. Default is ``*``
dayweek
The information to be set in the day of week section. Default is ``*``
comment
User comment to be added on line previous the cron job
commented
The cron job is set commented (prefixed with ``#DISABLED#``).
Defaults to False.
.. versionadded:: 2016.3.0
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
A special keyword to specify periodicity (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. versionadded:: 2016.3.0
'''
name = name.strip()
if identifier is False:
identifier = name
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron(user,
cmd=name,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
comment=comment,
commented=commented,
identifier=identifier,
special=special)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron {0} is set to be updated'.format(name)
return ret
if special is None:
data = __salt__['cron.set_job'](user=user,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
else:
data = __salt__['cron.set_special'](user=user,
special=special,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
if data == 'present':
ret['comment'] = 'Cron {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def absent(name,
user='root',
identifier=False,
special=None,
**kwargs):
'''
Verifies that the specified cron job is absent for the specified user; only
the name is matched when removing a cron job.
name
The command that should be absent in the user crontab.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
The special keyword used in the job (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
'''
# NOTE: The keyword arguments in **kwargs are ignored in this state, but
# cannot be removed from the function definition, otherwise the use
# of unsupported arguments will result in a traceback.
name = name.strip()
if identifier is False:
identifier = name
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron(user, name, identifier=identifier)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron {0} is set to be removed'.format(name)
return ret
if special is None:
data = __salt__['cron.rm_job'](user, name, identifier=identifier)
else:
data = __salt__['cron.rm_special'](user, name, special=special, identifier=identifier)
if data == 'absent':
ret['comment'] = "Cron {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
def file(name,
source_hash='',
source_hash_name=None,
user='root',
template=None,
context=None,
replace=True,
defaults=None,
backup='',
**kwargs):
'''
Provides file.managed-like functionality (templating, etc.) for a pre-made
crontab file, to be assigned to a given user.
name
The source file to be used as the crontab. This source file can be
hosted on either the salt master server, or on an HTTP or FTP server.
For files hosted on the salt file server, if the file is located on
the master in the directory named spam, and is called eggs, the source
string is ``salt://spam/eggs``
If the file is hosted on a HTTP or FTP server then the source_hash
argument is also required
source_hash
This can be either a file which contains a source hash string for
the source, or a source hash string. The source hash string is the
hash algorithm followed by the hash of the file:
``md5=e138491e9d5b97023cea823fe17bac22``
source_hash_name
When ``source_hash`` refers to a hash file, Salt will try to find the
correct hash by matching the filename/URI associated with that hash. By
default, Salt will look for the filename being managed. When managing a
file at path ``/tmp/foo.txt``, then the following line in a hash file
would match:
.. code-block:: text
acbd18db4cc2f85cedef654fccc4a4d8 foo.txt
However, sometimes a hash file will include multiple similar paths:
.. code-block:: text
37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt
acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt
73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt
In cases like this, Salt may match the incorrect hash. This argument
can be used to tell Salt which filename to match, to ensure that the
correct hash is identified. For example:
.. code-block:: yaml
foo_crontab:
cron.file:
- name: https://mydomain.tld/dir2/foo.txt
- source_hash: https://mydomain.tld/hashes
- source_hash_name: ./dir2/foo.txt
.. note::
This argument must contain the full filename entry from the
checksum file, as this argument is meant to disambiguate matches
for multiple files that have the same basename. So, in the
example above, simply using ``foo.txt`` would not match.
.. versionadded:: 2016.3.5
user
The user to whom the crontab should be assigned. This defaults to
root.
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently, jinja and mako are
supported.
context
Overrides default context variables passed to the template.
replace
If the crontab should be replaced, if False then this command will
be ignored if a crontab exists for the specified user. Default is True.
defaults
Default context passed to the template.
backup
Overrides the default backup mode for the user's crontab.
'''
# Initial set up
mode = '0600'
try:
group = __salt__['user.info'](user)['groups'][0]
except Exception:
ret = {'changes': {},
'comment': "Could not identify group for user {0}".format(user),
'name': name,
'result': False}
return ret
cron_path = salt.utils.files.mkstemp()
with salt.utils.files.fopen(cron_path, 'w+') as fp_:
raw_cron = __salt__['cron.raw_cron'](user)
if not raw_cron.endswith('\n'):
raw_cron = "{0}\n".format(raw_cron)
fp_.write(salt.utils.stringutils.to_str(raw_cron))
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
# Avoid variable naming confusion in below module calls, since ID
# declaration for this state will be a source URI.
source = name
if not replace and os.stat(cron_path).st_size > 0:
ret['comment'] = 'User {0} already has a crontab. No changes ' \
'made'.format(user)
os.unlink(cron_path)
return ret
if __opts__['test']:
fcm = __salt__['file.check_managed'](name=cron_path,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[], # no special attrs for cron
template=template,
context=context,
defaults=defaults,
saltenv=__env__,
**kwargs
)
ret['result'], ret['comment'] = fcm
os.unlink(cron_path)
return ret
# If the source is a list then find which file exists
source, source_hash = __salt__['file.source_list'](source,
source_hash,
__env__)
# Gather the source file from the server
try:
sfn, source_sum, comment = __salt__['file.get_managed'](
name=cron_path,
template=template,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
context=context,
defaults=defaults,
skip_verify=False, # skip_verify
**kwargs
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
if comment:
ret['comment'] = comment
ret['result'] = False
os.unlink(cron_path)
return ret
try:
ret = __salt__['file.manage_file'](
name=cron_path,
sfn=sfn,
ret=ret,
source=source,
source_sum=source_sum,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
backup=backup
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
cron_ret = None
if "diff" in ret['changes']:
cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path)
# Check cmd return code and show success or failure
if cron_ret['retcode'] == 0:
ret['comment'] = 'Crontab for user {0} was updated'.format(user)
ret['result'] = True
ret['changes'] = ret['changes']
else:
ret['comment'] = 'Unable to update user {0} crontab {1}.' \
' Error: {2}'.format(user, cron_path, cron_ret['stderr'])
ret['result'] = False
ret['changes'] = {}
elif ret['result']:
ret['comment'] = 'Crontab for user {0} is in the correct ' \
'state'.format(user)
ret['changes'] = {}
os.unlink(cron_path)
return ret
def env_present(name,
value=None,
user='root'):
'''
Verifies that the specified environment variable is present in the crontab
for the specified user.
name
The name of the environment variable to set in the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
value
The value to set for the given environment variable
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron_env(user, name, value=value)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron env {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron env {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron env {0} is set to be updated'.format(name)
return ret
data = __salt__['cron.set_env'](user, name, value=value)
if data == 'present':
ret['comment'] = 'Cron env {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron env {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron env {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron env {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def env_absent(name,
user='root'):
'''
Verifies that the specified environment variable is absent from the crontab
for the specified user
name
The name of the environment variable to remove from the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
'''
name = name.strip()
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron_env(user, name)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron env {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron env {0} is set to be removed'.format(name)
return ret
data = __salt__['cron.rm_env'](user, name)
if data == 'absent':
ret['comment'] = "Cron env {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron env {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron env {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/cron.py
|
_check_cron_env
|
python
|
def _check_cron_env(user,
name,
value=None):
'''
Return the environment changes
'''
if value is None:
value = "" # Matching value set in salt.modules.cron._render_tab
lst = __salt__['cron.list_tab'](user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
return 'update'
return 'present'
return 'absent'
|
Return the environment changes
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L217-L231
| null |
# -*- coding: utf-8 -*-
'''
Management of cron, the Unix command scheduler
==============================================
Cron declarations require a number of parameters. The following are the
parameters used by Salt to define the various timing values for a cron job:
* ``minute``
* ``hour``
* ``daymonth``
* ``month``
* ``dayweek`` (0 to 6 are Sunday through Saturday, 7 can also be used for
Sunday)
.. warning::
Any timing arguments not specified take a value of ``*``. This means that
setting ``hour`` to ``5``, while not defining the ``minute`` param, will
result in Salt adding a job that will execute every minute between 5 and 6
A.M.!
Additionally, the default user for these states is ``root``. Therefore, if
the cron job is for another user, it is necessary to specify that user with
the ``user`` parameter.
A long time ago (before 2014.2), when making changes to an existing cron job,
the name declaration is the parameter used to uniquely identify the job,
so if an existing cron that looks like this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 5
Is changed to this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 7
- hour: 2
Then the existing cron will be updated, but if the cron command is changed,
then a new cron job will be added to the user's crontab.
The current behavior is still relying on that mechanism, but you can also
specify an identifier to identify your crontabs:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 7
- hour: 2
.. versionadded:: 2014.1.2
And, some months later, you modify it:
.. code-block:: yaml
superscript > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 3
- hour: 4
.. versionadded:: 2014.1.2
The old **date > /tmp/crontest** will be replaced by
**superscript > /tmp/crontest**.
Additionally, Salt also supports running a cron every ``x minutes`` very similarly to the Unix
convention of using ``*/5`` to have a job run every five minutes. In Salt, this
looks like:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: '*/5'
The job will now run every 5 minutes.
Additionally, the temporal parameters (minute, hour, etc.) can be randomized by
using ``random`` instead of using a specific value. For example, by using the
``random`` keyword in the ``minute`` parameter of a cron state, the same cron
job can be pushed to hundreds or thousands of hosts, and they would each use a
randomly-generated minute. This can be helpful when the cron job accesses a
network resource, and it is not desirable for all hosts to run the job
concurrently.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- minute: random
- hour: 2
.. versionadded:: 0.16.0
Since Salt assumes a value of ``*`` for unspecified temporal parameters, adding
a parameter to the state and setting it to ``random`` will change that value
from ``*`` to a randomized numeric value. However, if that field in the cron
entry on the minion already contains a numeric value, then using the ``random``
keyword will not modify it.
Added the opportunity to set a job with a special keyword like '@reboot' or
'@hourly'. Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- special: '@hourly'
The script will be executed every reboot if cron daemon support this option.
.. code-block:: yaml
/path/to/cron/otherscript:
cron.absent:
- user: root
- special: '@daily'
This counter part definition will ensure than a job with a special keyword
is not set.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
# Import salt libs
import salt.utils.files
from salt.modules.cron import (
_needs_change,
_cron_matched
)
from salt.ext import six
def __virtual__():
if 'cron.list_tab' in __salt__:
return True
else:
return (False, 'cron module could not be loaded')
def _check_cron(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
comment=None,
commented=None,
identifier=None,
special=None):
'''
Return the changes
'''
if minute is not None:
minute = six.text_type(minute).lower()
if hour is not None:
hour = six.text_type(hour).lower()
if daymonth is not None:
daymonth = six.text_type(daymonth).lower()
if month is not None:
month = six.text_type(month).lower()
if dayweek is not None:
dayweek = six.text_type(dayweek).lower()
if identifier is not None:
identifier = six.text_type(identifier)
if commented is not None:
commented = commented is True
if cmd is not None:
cmd = six.text_type(cmd)
lst = __salt__['cron.list_tab'](user)
if special is None:
for cron in lst['crons']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['minute'], minute), (cron['hour'], hour),
(cron['daymonth'], daymonth), (cron['month'], month),
(cron['dayweek'], dayweek), (cron['identifier'], identifier),
(cron['cmd'], cmd), (cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
else:
for cron in lst['special']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['spec'], special),
(cron['identifier'], identifier),
(cron['cmd'], cmd),
(cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
return 'absent'
def _get_cron_info():
'''
Returns the proper group owner and path to the cron directory
'''
owner = 'root'
if __grains__['os'] == 'FreeBSD':
group = 'wheel'
crontab_dir = '/var/cron/tabs'
elif __grains__['os'] == 'OpenBSD':
group = 'crontab'
crontab_dir = '/var/cron/tabs'
elif __grains__['os_family'] == 'Solaris':
group = 'root'
crontab_dir = '/var/spool/cron/crontabs'
elif __grains__['os'] == 'MacOS':
group = 'wheel'
crontab_dir = '/usr/lib/cron/tabs'
else:
group = 'root'
crontab_dir = '/var/spool/cron'
return owner, group, crontab_dir
def present(name,
user='root',
minute='*',
hour='*',
daymonth='*',
month='*',
dayweek='*',
comment=None,
commented=False,
identifier=False,
special=None):
'''
Verifies that the specified cron job is present for the specified user.
It is recommended to use `identifier`. Otherwise the cron job is installed
twice if you change the name.
For more advanced information about what exactly can be set in the cron
timing parameters, check your cron system's documentation. Most Unix-like
systems' cron documentation can be found via the crontab man page:
``man 5 crontab``.
name
The command that should be executed by the cron job.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
minute
The information to be set into the minute section, this can be any
string supported by your cron system's the minute field. Default is
``*``
hour
The information to be set in the hour section. Default is ``*``
daymonth
The information to be set in the day of month section. Default is ``*``
month
The information to be set in the month section. Default is ``*``
dayweek
The information to be set in the day of week section. Default is ``*``
comment
User comment to be added on line previous the cron job
commented
The cron job is set commented (prefixed with ``#DISABLED#``).
Defaults to False.
.. versionadded:: 2016.3.0
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
A special keyword to specify periodicity (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. versionadded:: 2016.3.0
'''
name = name.strip()
if identifier is False:
identifier = name
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron(user,
cmd=name,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
comment=comment,
commented=commented,
identifier=identifier,
special=special)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron {0} is set to be updated'.format(name)
return ret
if special is None:
data = __salt__['cron.set_job'](user=user,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
else:
data = __salt__['cron.set_special'](user=user,
special=special,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
if data == 'present':
ret['comment'] = 'Cron {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def absent(name,
user='root',
identifier=False,
special=None,
**kwargs):
'''
Verifies that the specified cron job is absent for the specified user; only
the name is matched when removing a cron job.
name
The command that should be absent in the user crontab.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
The special keyword used in the job (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
'''
# NOTE: The keyword arguments in **kwargs are ignored in this state, but
# cannot be removed from the function definition, otherwise the use
# of unsupported arguments will result in a traceback.
name = name.strip()
if identifier is False:
identifier = name
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron(user, name, identifier=identifier)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron {0} is set to be removed'.format(name)
return ret
if special is None:
data = __salt__['cron.rm_job'](user, name, identifier=identifier)
else:
data = __salt__['cron.rm_special'](user, name, special=special, identifier=identifier)
if data == 'absent':
ret['comment'] = "Cron {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
def file(name,
source_hash='',
source_hash_name=None,
user='root',
template=None,
context=None,
replace=True,
defaults=None,
backup='',
**kwargs):
'''
Provides file.managed-like functionality (templating, etc.) for a pre-made
crontab file, to be assigned to a given user.
name
The source file to be used as the crontab. This source file can be
hosted on either the salt master server, or on an HTTP or FTP server.
For files hosted on the salt file server, if the file is located on
the master in the directory named spam, and is called eggs, the source
string is ``salt://spam/eggs``
If the file is hosted on a HTTP or FTP server then the source_hash
argument is also required
source_hash
This can be either a file which contains a source hash string for
the source, or a source hash string. The source hash string is the
hash algorithm followed by the hash of the file:
``md5=e138491e9d5b97023cea823fe17bac22``
source_hash_name
When ``source_hash`` refers to a hash file, Salt will try to find the
correct hash by matching the filename/URI associated with that hash. By
default, Salt will look for the filename being managed. When managing a
file at path ``/tmp/foo.txt``, then the following line in a hash file
would match:
.. code-block:: text
acbd18db4cc2f85cedef654fccc4a4d8 foo.txt
However, sometimes a hash file will include multiple similar paths:
.. code-block:: text
37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt
acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt
73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt
In cases like this, Salt may match the incorrect hash. This argument
can be used to tell Salt which filename to match, to ensure that the
correct hash is identified. For example:
.. code-block:: yaml
foo_crontab:
cron.file:
- name: https://mydomain.tld/dir2/foo.txt
- source_hash: https://mydomain.tld/hashes
- source_hash_name: ./dir2/foo.txt
.. note::
This argument must contain the full filename entry from the
checksum file, as this argument is meant to disambiguate matches
for multiple files that have the same basename. So, in the
example above, simply using ``foo.txt`` would not match.
.. versionadded:: 2016.3.5
user
The user to whom the crontab should be assigned. This defaults to
root.
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently, jinja and mako are
supported.
context
Overrides default context variables passed to the template.
replace
If the crontab should be replaced, if False then this command will
be ignored if a crontab exists for the specified user. Default is True.
defaults
Default context passed to the template.
backup
Overrides the default backup mode for the user's crontab.
'''
# Initial set up
mode = '0600'
try:
group = __salt__['user.info'](user)['groups'][0]
except Exception:
ret = {'changes': {},
'comment': "Could not identify group for user {0}".format(user),
'name': name,
'result': False}
return ret
cron_path = salt.utils.files.mkstemp()
with salt.utils.files.fopen(cron_path, 'w+') as fp_:
raw_cron = __salt__['cron.raw_cron'](user)
if not raw_cron.endswith('\n'):
raw_cron = "{0}\n".format(raw_cron)
fp_.write(salt.utils.stringutils.to_str(raw_cron))
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
# Avoid variable naming confusion in below module calls, since ID
# declaration for this state will be a source URI.
source = name
if not replace and os.stat(cron_path).st_size > 0:
ret['comment'] = 'User {0} already has a crontab. No changes ' \
'made'.format(user)
os.unlink(cron_path)
return ret
if __opts__['test']:
fcm = __salt__['file.check_managed'](name=cron_path,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[], # no special attrs for cron
template=template,
context=context,
defaults=defaults,
saltenv=__env__,
**kwargs
)
ret['result'], ret['comment'] = fcm
os.unlink(cron_path)
return ret
# If the source is a list then find which file exists
source, source_hash = __salt__['file.source_list'](source,
source_hash,
__env__)
# Gather the source file from the server
try:
sfn, source_sum, comment = __salt__['file.get_managed'](
name=cron_path,
template=template,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
context=context,
defaults=defaults,
skip_verify=False, # skip_verify
**kwargs
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
if comment:
ret['comment'] = comment
ret['result'] = False
os.unlink(cron_path)
return ret
try:
ret = __salt__['file.manage_file'](
name=cron_path,
sfn=sfn,
ret=ret,
source=source,
source_sum=source_sum,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
backup=backup
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
cron_ret = None
if "diff" in ret['changes']:
cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path)
# Check cmd return code and show success or failure
if cron_ret['retcode'] == 0:
ret['comment'] = 'Crontab for user {0} was updated'.format(user)
ret['result'] = True
ret['changes'] = ret['changes']
else:
ret['comment'] = 'Unable to update user {0} crontab {1}.' \
' Error: {2}'.format(user, cron_path, cron_ret['stderr'])
ret['result'] = False
ret['changes'] = {}
elif ret['result']:
ret['comment'] = 'Crontab for user {0} is in the correct ' \
'state'.format(user)
ret['changes'] = {}
os.unlink(cron_path)
return ret
def env_present(name,
value=None,
user='root'):
'''
Verifies that the specified environment variable is present in the crontab
for the specified user.
name
The name of the environment variable to set in the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
value
The value to set for the given environment variable
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron_env(user, name, value=value)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron env {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron env {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron env {0} is set to be updated'.format(name)
return ret
data = __salt__['cron.set_env'](user, name, value=value)
if data == 'present':
ret['comment'] = 'Cron env {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron env {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron env {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron env {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def env_absent(name,
user='root'):
'''
Verifies that the specified environment variable is absent from the crontab
for the specified user
name
The name of the environment variable to remove from the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
'''
name = name.strip()
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron_env(user, name)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron env {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron env {0} is set to be removed'.format(name)
return ret
data = __salt__['cron.rm_env'](user, name)
if data == 'absent':
ret['comment'] = "Cron env {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron env {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron env {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/cron.py
|
_get_cron_info
|
python
|
def _get_cron_info():
'''
Returns the proper group owner and path to the cron directory
'''
owner = 'root'
if __grains__['os'] == 'FreeBSD':
group = 'wheel'
crontab_dir = '/var/cron/tabs'
elif __grains__['os'] == 'OpenBSD':
group = 'crontab'
crontab_dir = '/var/cron/tabs'
elif __grains__['os_family'] == 'Solaris':
group = 'root'
crontab_dir = '/var/spool/cron/crontabs'
elif __grains__['os'] == 'MacOS':
group = 'wheel'
crontab_dir = '/usr/lib/cron/tabs'
else:
group = 'root'
crontab_dir = '/var/spool/cron'
return owner, group, crontab_dir
|
Returns the proper group owner and path to the cron directory
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L234-L254
| null |
# -*- coding: utf-8 -*-
'''
Management of cron, the Unix command scheduler
==============================================
Cron declarations require a number of parameters. The following are the
parameters used by Salt to define the various timing values for a cron job:
* ``minute``
* ``hour``
* ``daymonth``
* ``month``
* ``dayweek`` (0 to 6 are Sunday through Saturday, 7 can also be used for
Sunday)
.. warning::
Any timing arguments not specified take a value of ``*``. This means that
setting ``hour`` to ``5``, while not defining the ``minute`` param, will
result in Salt adding a job that will execute every minute between 5 and 6
A.M.!
Additionally, the default user for these states is ``root``. Therefore, if
the cron job is for another user, it is necessary to specify that user with
the ``user`` parameter.
A long time ago (before 2014.2), when making changes to an existing cron job,
the name declaration is the parameter used to uniquely identify the job,
so if an existing cron that looks like this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 5
Is changed to this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 7
- hour: 2
Then the existing cron will be updated, but if the cron command is changed,
then a new cron job will be added to the user's crontab.
The current behavior is still relying on that mechanism, but you can also
specify an identifier to identify your crontabs:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 7
- hour: 2
.. versionadded:: 2014.1.2
And, some months later, you modify it:
.. code-block:: yaml
superscript > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 3
- hour: 4
.. versionadded:: 2014.1.2
The old **date > /tmp/crontest** will be replaced by
**superscript > /tmp/crontest**.
Additionally, Salt also supports running a cron every ``x minutes`` very similarly to the Unix
convention of using ``*/5`` to have a job run every five minutes. In Salt, this
looks like:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: '*/5'
The job will now run every 5 minutes.
Additionally, the temporal parameters (minute, hour, etc.) can be randomized by
using ``random`` instead of using a specific value. For example, by using the
``random`` keyword in the ``minute`` parameter of a cron state, the same cron
job can be pushed to hundreds or thousands of hosts, and they would each use a
randomly-generated minute. This can be helpful when the cron job accesses a
network resource, and it is not desirable for all hosts to run the job
concurrently.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- minute: random
- hour: 2
.. versionadded:: 0.16.0
Since Salt assumes a value of ``*`` for unspecified temporal parameters, adding
a parameter to the state and setting it to ``random`` will change that value
from ``*`` to a randomized numeric value. However, if that field in the cron
entry on the minion already contains a numeric value, then using the ``random``
keyword will not modify it.
Added the opportunity to set a job with a special keyword like '@reboot' or
'@hourly'. Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- special: '@hourly'
The script will be executed every reboot if cron daemon support this option.
.. code-block:: yaml
/path/to/cron/otherscript:
cron.absent:
- user: root
- special: '@daily'
This counter part definition will ensure than a job with a special keyword
is not set.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
# Import salt libs
import salt.utils.files
from salt.modules.cron import (
_needs_change,
_cron_matched
)
from salt.ext import six
def __virtual__():
if 'cron.list_tab' in __salt__:
return True
else:
return (False, 'cron module could not be loaded')
def _check_cron(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
comment=None,
commented=None,
identifier=None,
special=None):
'''
Return the changes
'''
if minute is not None:
minute = six.text_type(minute).lower()
if hour is not None:
hour = six.text_type(hour).lower()
if daymonth is not None:
daymonth = six.text_type(daymonth).lower()
if month is not None:
month = six.text_type(month).lower()
if dayweek is not None:
dayweek = six.text_type(dayweek).lower()
if identifier is not None:
identifier = six.text_type(identifier)
if commented is not None:
commented = commented is True
if cmd is not None:
cmd = six.text_type(cmd)
lst = __salt__['cron.list_tab'](user)
if special is None:
for cron in lst['crons']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['minute'], minute), (cron['hour'], hour),
(cron['daymonth'], daymonth), (cron['month'], month),
(cron['dayweek'], dayweek), (cron['identifier'], identifier),
(cron['cmd'], cmd), (cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
else:
for cron in lst['special']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['spec'], special),
(cron['identifier'], identifier),
(cron['cmd'], cmd),
(cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
return 'absent'
def _check_cron_env(user,
name,
value=None):
'''
Return the environment changes
'''
if value is None:
value = "" # Matching value set in salt.modules.cron._render_tab
lst = __salt__['cron.list_tab'](user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
return 'update'
return 'present'
return 'absent'
def present(name,
user='root',
minute='*',
hour='*',
daymonth='*',
month='*',
dayweek='*',
comment=None,
commented=False,
identifier=False,
special=None):
'''
Verifies that the specified cron job is present for the specified user.
It is recommended to use `identifier`. Otherwise the cron job is installed
twice if you change the name.
For more advanced information about what exactly can be set in the cron
timing parameters, check your cron system's documentation. Most Unix-like
systems' cron documentation can be found via the crontab man page:
``man 5 crontab``.
name
The command that should be executed by the cron job.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
minute
The information to be set into the minute section, this can be any
string supported by your cron system's the minute field. Default is
``*``
hour
The information to be set in the hour section. Default is ``*``
daymonth
The information to be set in the day of month section. Default is ``*``
month
The information to be set in the month section. Default is ``*``
dayweek
The information to be set in the day of week section. Default is ``*``
comment
User comment to be added on line previous the cron job
commented
The cron job is set commented (prefixed with ``#DISABLED#``).
Defaults to False.
.. versionadded:: 2016.3.0
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
A special keyword to specify periodicity (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. versionadded:: 2016.3.0
'''
name = name.strip()
if identifier is False:
identifier = name
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron(user,
cmd=name,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
comment=comment,
commented=commented,
identifier=identifier,
special=special)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron {0} is set to be updated'.format(name)
return ret
if special is None:
data = __salt__['cron.set_job'](user=user,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
else:
data = __salt__['cron.set_special'](user=user,
special=special,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
if data == 'present':
ret['comment'] = 'Cron {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def absent(name,
user='root',
identifier=False,
special=None,
**kwargs):
'''
Verifies that the specified cron job is absent for the specified user; only
the name is matched when removing a cron job.
name
The command that should be absent in the user crontab.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
The special keyword used in the job (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
'''
# NOTE: The keyword arguments in **kwargs are ignored in this state, but
# cannot be removed from the function definition, otherwise the use
# of unsupported arguments will result in a traceback.
name = name.strip()
if identifier is False:
identifier = name
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron(user, name, identifier=identifier)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron {0} is set to be removed'.format(name)
return ret
if special is None:
data = __salt__['cron.rm_job'](user, name, identifier=identifier)
else:
data = __salt__['cron.rm_special'](user, name, special=special, identifier=identifier)
if data == 'absent':
ret['comment'] = "Cron {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
def file(name,
source_hash='',
source_hash_name=None,
user='root',
template=None,
context=None,
replace=True,
defaults=None,
backup='',
**kwargs):
'''
Provides file.managed-like functionality (templating, etc.) for a pre-made
crontab file, to be assigned to a given user.
name
The source file to be used as the crontab. This source file can be
hosted on either the salt master server, or on an HTTP or FTP server.
For files hosted on the salt file server, if the file is located on
the master in the directory named spam, and is called eggs, the source
string is ``salt://spam/eggs``
If the file is hosted on a HTTP or FTP server then the source_hash
argument is also required
source_hash
This can be either a file which contains a source hash string for
the source, or a source hash string. The source hash string is the
hash algorithm followed by the hash of the file:
``md5=e138491e9d5b97023cea823fe17bac22``
source_hash_name
When ``source_hash`` refers to a hash file, Salt will try to find the
correct hash by matching the filename/URI associated with that hash. By
default, Salt will look for the filename being managed. When managing a
file at path ``/tmp/foo.txt``, then the following line in a hash file
would match:
.. code-block:: text
acbd18db4cc2f85cedef654fccc4a4d8 foo.txt
However, sometimes a hash file will include multiple similar paths:
.. code-block:: text
37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt
acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt
73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt
In cases like this, Salt may match the incorrect hash. This argument
can be used to tell Salt which filename to match, to ensure that the
correct hash is identified. For example:
.. code-block:: yaml
foo_crontab:
cron.file:
- name: https://mydomain.tld/dir2/foo.txt
- source_hash: https://mydomain.tld/hashes
- source_hash_name: ./dir2/foo.txt
.. note::
This argument must contain the full filename entry from the
checksum file, as this argument is meant to disambiguate matches
for multiple files that have the same basename. So, in the
example above, simply using ``foo.txt`` would not match.
.. versionadded:: 2016.3.5
user
The user to whom the crontab should be assigned. This defaults to
root.
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently, jinja and mako are
supported.
context
Overrides default context variables passed to the template.
replace
If the crontab should be replaced, if False then this command will
be ignored if a crontab exists for the specified user. Default is True.
defaults
Default context passed to the template.
backup
Overrides the default backup mode for the user's crontab.
'''
# Initial set up
mode = '0600'
try:
group = __salt__['user.info'](user)['groups'][0]
except Exception:
ret = {'changes': {},
'comment': "Could not identify group for user {0}".format(user),
'name': name,
'result': False}
return ret
cron_path = salt.utils.files.mkstemp()
with salt.utils.files.fopen(cron_path, 'w+') as fp_:
raw_cron = __salt__['cron.raw_cron'](user)
if not raw_cron.endswith('\n'):
raw_cron = "{0}\n".format(raw_cron)
fp_.write(salt.utils.stringutils.to_str(raw_cron))
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
# Avoid variable naming confusion in below module calls, since ID
# declaration for this state will be a source URI.
source = name
if not replace and os.stat(cron_path).st_size > 0:
ret['comment'] = 'User {0} already has a crontab. No changes ' \
'made'.format(user)
os.unlink(cron_path)
return ret
if __opts__['test']:
fcm = __salt__['file.check_managed'](name=cron_path,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[], # no special attrs for cron
template=template,
context=context,
defaults=defaults,
saltenv=__env__,
**kwargs
)
ret['result'], ret['comment'] = fcm
os.unlink(cron_path)
return ret
# If the source is a list then find which file exists
source, source_hash = __salt__['file.source_list'](source,
source_hash,
__env__)
# Gather the source file from the server
try:
sfn, source_sum, comment = __salt__['file.get_managed'](
name=cron_path,
template=template,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
context=context,
defaults=defaults,
skip_verify=False, # skip_verify
**kwargs
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
if comment:
ret['comment'] = comment
ret['result'] = False
os.unlink(cron_path)
return ret
try:
ret = __salt__['file.manage_file'](
name=cron_path,
sfn=sfn,
ret=ret,
source=source,
source_sum=source_sum,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
backup=backup
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
cron_ret = None
if "diff" in ret['changes']:
cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path)
# Check cmd return code and show success or failure
if cron_ret['retcode'] == 0:
ret['comment'] = 'Crontab for user {0} was updated'.format(user)
ret['result'] = True
ret['changes'] = ret['changes']
else:
ret['comment'] = 'Unable to update user {0} crontab {1}.' \
' Error: {2}'.format(user, cron_path, cron_ret['stderr'])
ret['result'] = False
ret['changes'] = {}
elif ret['result']:
ret['comment'] = 'Crontab for user {0} is in the correct ' \
'state'.format(user)
ret['changes'] = {}
os.unlink(cron_path)
return ret
def env_present(name,
value=None,
user='root'):
'''
Verifies that the specified environment variable is present in the crontab
for the specified user.
name
The name of the environment variable to set in the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
value
The value to set for the given environment variable
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron_env(user, name, value=value)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron env {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron env {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron env {0} is set to be updated'.format(name)
return ret
data = __salt__['cron.set_env'](user, name, value=value)
if data == 'present':
ret['comment'] = 'Cron env {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron env {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron env {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron env {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def env_absent(name,
user='root'):
'''
Verifies that the specified environment variable is absent from the crontab
for the specified user
name
The name of the environment variable to remove from the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
'''
name = name.strip()
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron_env(user, name)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron env {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron env {0} is set to be removed'.format(name)
return ret
data = __salt__['cron.rm_env'](user, name)
if data == 'absent':
ret['comment'] = "Cron env {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron env {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron env {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/cron.py
|
present
|
python
|
def present(name,
user='root',
minute='*',
hour='*',
daymonth='*',
month='*',
dayweek='*',
comment=None,
commented=False,
identifier=False,
special=None):
'''
Verifies that the specified cron job is present for the specified user.
It is recommended to use `identifier`. Otherwise the cron job is installed
twice if you change the name.
For more advanced information about what exactly can be set in the cron
timing parameters, check your cron system's documentation. Most Unix-like
systems' cron documentation can be found via the crontab man page:
``man 5 crontab``.
name
The command that should be executed by the cron job.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
minute
The information to be set into the minute section, this can be any
string supported by your cron system's the minute field. Default is
``*``
hour
The information to be set in the hour section. Default is ``*``
daymonth
The information to be set in the day of month section. Default is ``*``
month
The information to be set in the month section. Default is ``*``
dayweek
The information to be set in the day of week section. Default is ``*``
comment
User comment to be added on line previous the cron job
commented
The cron job is set commented (prefixed with ``#DISABLED#``).
Defaults to False.
.. versionadded:: 2016.3.0
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
A special keyword to specify periodicity (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. versionadded:: 2016.3.0
'''
name = name.strip()
if identifier is False:
identifier = name
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron(user,
cmd=name,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
comment=comment,
commented=commented,
identifier=identifier,
special=special)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron {0} is set to be updated'.format(name)
return ret
if special is None:
data = __salt__['cron.set_job'](user=user,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
else:
data = __salt__['cron.set_special'](user=user,
special=special,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
if data == 'present':
ret['comment'] = 'Cron {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
|
Verifies that the specified cron job is present for the specified user.
It is recommended to use `identifier`. Otherwise the cron job is installed
twice if you change the name.
For more advanced information about what exactly can be set in the cron
timing parameters, check your cron system's documentation. Most Unix-like
systems' cron documentation can be found via the crontab man page:
``man 5 crontab``.
name
The command that should be executed by the cron job.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
minute
The information to be set into the minute section, this can be any
string supported by your cron system's the minute field. Default is
``*``
hour
The information to be set in the hour section. Default is ``*``
daymonth
The information to be set in the day of month section. Default is ``*``
month
The information to be set in the month section. Default is ``*``
dayweek
The information to be set in the day of week section. Default is ``*``
comment
User comment to be added on line previous the cron job
commented
The cron job is set commented (prefixed with ``#DISABLED#``).
Defaults to False.
.. versionadded:: 2016.3.0
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
A special keyword to specify periodicity (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. versionadded:: 2016.3.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L257-L383
|
[
"def _check_cron(user,\n cmd,\n minute=None,\n hour=None,\n daymonth=None,\n month=None,\n dayweek=None,\n comment=None,\n commented=None,\n identifier=None,\n special=None):\n '''\n Return the changes\n '''\n if minute is not None:\n minute = six.text_type(minute).lower()\n if hour is not None:\n hour = six.text_type(hour).lower()\n if daymonth is not None:\n daymonth = six.text_type(daymonth).lower()\n if month is not None:\n month = six.text_type(month).lower()\n if dayweek is not None:\n dayweek = six.text_type(dayweek).lower()\n if identifier is not None:\n identifier = six.text_type(identifier)\n if commented is not None:\n commented = commented is True\n if cmd is not None:\n cmd = six.text_type(cmd)\n lst = __salt__['cron.list_tab'](user)\n if special is None:\n for cron in lst['crons']:\n if _cron_matched(cron, cmd, identifier):\n if any([_needs_change(x, y) for x, y in\n ((cron['minute'], minute), (cron['hour'], hour),\n (cron['daymonth'], daymonth), (cron['month'], month),\n (cron['dayweek'], dayweek), (cron['identifier'], identifier),\n (cron['cmd'], cmd), (cron['comment'], comment),\n (cron['commented'], commented))]):\n return 'update'\n return 'present'\n else:\n for cron in lst['special']:\n if _cron_matched(cron, cmd, identifier):\n if any([_needs_change(x, y) for x, y in\n ((cron['spec'], special),\n (cron['identifier'], identifier),\n (cron['cmd'], cmd),\n (cron['comment'], comment),\n (cron['commented'], commented))]):\n return 'update'\n return 'present'\n return 'absent'\n"
] |
# -*- coding: utf-8 -*-
'''
Management of cron, the Unix command scheduler
==============================================
Cron declarations require a number of parameters. The following are the
parameters used by Salt to define the various timing values for a cron job:
* ``minute``
* ``hour``
* ``daymonth``
* ``month``
* ``dayweek`` (0 to 6 are Sunday through Saturday, 7 can also be used for
Sunday)
.. warning::
Any timing arguments not specified take a value of ``*``. This means that
setting ``hour`` to ``5``, while not defining the ``minute`` param, will
result in Salt adding a job that will execute every minute between 5 and 6
A.M.!
Additionally, the default user for these states is ``root``. Therefore, if
the cron job is for another user, it is necessary to specify that user with
the ``user`` parameter.
A long time ago (before 2014.2), when making changes to an existing cron job,
the name declaration is the parameter used to uniquely identify the job,
so if an existing cron that looks like this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 5
Is changed to this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 7
- hour: 2
Then the existing cron will be updated, but if the cron command is changed,
then a new cron job will be added to the user's crontab.
The current behavior is still relying on that mechanism, but you can also
specify an identifier to identify your crontabs:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 7
- hour: 2
.. versionadded:: 2014.1.2
And, some months later, you modify it:
.. code-block:: yaml
superscript > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 3
- hour: 4
.. versionadded:: 2014.1.2
The old **date > /tmp/crontest** will be replaced by
**superscript > /tmp/crontest**.
Additionally, Salt also supports running a cron every ``x minutes`` very similarly to the Unix
convention of using ``*/5`` to have a job run every five minutes. In Salt, this
looks like:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: '*/5'
The job will now run every 5 minutes.
Additionally, the temporal parameters (minute, hour, etc.) can be randomized by
using ``random`` instead of using a specific value. For example, by using the
``random`` keyword in the ``minute`` parameter of a cron state, the same cron
job can be pushed to hundreds or thousands of hosts, and they would each use a
randomly-generated minute. This can be helpful when the cron job accesses a
network resource, and it is not desirable for all hosts to run the job
concurrently.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- minute: random
- hour: 2
.. versionadded:: 0.16.0
Since Salt assumes a value of ``*`` for unspecified temporal parameters, adding
a parameter to the state and setting it to ``random`` will change that value
from ``*`` to a randomized numeric value. However, if that field in the cron
entry on the minion already contains a numeric value, then using the ``random``
keyword will not modify it.
Added the opportunity to set a job with a special keyword like '@reboot' or
'@hourly'. Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- special: '@hourly'
The script will be executed every reboot if cron daemon support this option.
.. code-block:: yaml
/path/to/cron/otherscript:
cron.absent:
- user: root
- special: '@daily'
This counter part definition will ensure than a job with a special keyword
is not set.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
# Import salt libs
import salt.utils.files
from salt.modules.cron import (
_needs_change,
_cron_matched
)
from salt.ext import six
def __virtual__():
if 'cron.list_tab' in __salt__:
return True
else:
return (False, 'cron module could not be loaded')
def _check_cron(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
comment=None,
commented=None,
identifier=None,
special=None):
'''
Return the changes
'''
if minute is not None:
minute = six.text_type(minute).lower()
if hour is not None:
hour = six.text_type(hour).lower()
if daymonth is not None:
daymonth = six.text_type(daymonth).lower()
if month is not None:
month = six.text_type(month).lower()
if dayweek is not None:
dayweek = six.text_type(dayweek).lower()
if identifier is not None:
identifier = six.text_type(identifier)
if commented is not None:
commented = commented is True
if cmd is not None:
cmd = six.text_type(cmd)
lst = __salt__['cron.list_tab'](user)
if special is None:
for cron in lst['crons']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['minute'], minute), (cron['hour'], hour),
(cron['daymonth'], daymonth), (cron['month'], month),
(cron['dayweek'], dayweek), (cron['identifier'], identifier),
(cron['cmd'], cmd), (cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
else:
for cron in lst['special']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['spec'], special),
(cron['identifier'], identifier),
(cron['cmd'], cmd),
(cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
return 'absent'
def _check_cron_env(user,
name,
value=None):
'''
Return the environment changes
'''
if value is None:
value = "" # Matching value set in salt.modules.cron._render_tab
lst = __salt__['cron.list_tab'](user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
return 'update'
return 'present'
return 'absent'
def _get_cron_info():
'''
Returns the proper group owner and path to the cron directory
'''
owner = 'root'
if __grains__['os'] == 'FreeBSD':
group = 'wheel'
crontab_dir = '/var/cron/tabs'
elif __grains__['os'] == 'OpenBSD':
group = 'crontab'
crontab_dir = '/var/cron/tabs'
elif __grains__['os_family'] == 'Solaris':
group = 'root'
crontab_dir = '/var/spool/cron/crontabs'
elif __grains__['os'] == 'MacOS':
group = 'wheel'
crontab_dir = '/usr/lib/cron/tabs'
else:
group = 'root'
crontab_dir = '/var/spool/cron'
return owner, group, crontab_dir
def absent(name,
user='root',
identifier=False,
special=None,
**kwargs):
'''
Verifies that the specified cron job is absent for the specified user; only
the name is matched when removing a cron job.
name
The command that should be absent in the user crontab.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
The special keyword used in the job (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
'''
# NOTE: The keyword arguments in **kwargs are ignored in this state, but
# cannot be removed from the function definition, otherwise the use
# of unsupported arguments will result in a traceback.
name = name.strip()
if identifier is False:
identifier = name
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron(user, name, identifier=identifier)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron {0} is set to be removed'.format(name)
return ret
if special is None:
data = __salt__['cron.rm_job'](user, name, identifier=identifier)
else:
data = __salt__['cron.rm_special'](user, name, special=special, identifier=identifier)
if data == 'absent':
ret['comment'] = "Cron {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
def file(name,
source_hash='',
source_hash_name=None,
user='root',
template=None,
context=None,
replace=True,
defaults=None,
backup='',
**kwargs):
'''
Provides file.managed-like functionality (templating, etc.) for a pre-made
crontab file, to be assigned to a given user.
name
The source file to be used as the crontab. This source file can be
hosted on either the salt master server, or on an HTTP or FTP server.
For files hosted on the salt file server, if the file is located on
the master in the directory named spam, and is called eggs, the source
string is ``salt://spam/eggs``
If the file is hosted on a HTTP or FTP server then the source_hash
argument is also required
source_hash
This can be either a file which contains a source hash string for
the source, or a source hash string. The source hash string is the
hash algorithm followed by the hash of the file:
``md5=e138491e9d5b97023cea823fe17bac22``
source_hash_name
When ``source_hash`` refers to a hash file, Salt will try to find the
correct hash by matching the filename/URI associated with that hash. By
default, Salt will look for the filename being managed. When managing a
file at path ``/tmp/foo.txt``, then the following line in a hash file
would match:
.. code-block:: text
acbd18db4cc2f85cedef654fccc4a4d8 foo.txt
However, sometimes a hash file will include multiple similar paths:
.. code-block:: text
37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt
acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt
73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt
In cases like this, Salt may match the incorrect hash. This argument
can be used to tell Salt which filename to match, to ensure that the
correct hash is identified. For example:
.. code-block:: yaml
foo_crontab:
cron.file:
- name: https://mydomain.tld/dir2/foo.txt
- source_hash: https://mydomain.tld/hashes
- source_hash_name: ./dir2/foo.txt
.. note::
This argument must contain the full filename entry from the
checksum file, as this argument is meant to disambiguate matches
for multiple files that have the same basename. So, in the
example above, simply using ``foo.txt`` would not match.
.. versionadded:: 2016.3.5
user
The user to whom the crontab should be assigned. This defaults to
root.
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently, jinja and mako are
supported.
context
Overrides default context variables passed to the template.
replace
If the crontab should be replaced, if False then this command will
be ignored if a crontab exists for the specified user. Default is True.
defaults
Default context passed to the template.
backup
Overrides the default backup mode for the user's crontab.
'''
# Initial set up
mode = '0600'
try:
group = __salt__['user.info'](user)['groups'][0]
except Exception:
ret = {'changes': {},
'comment': "Could not identify group for user {0}".format(user),
'name': name,
'result': False}
return ret
cron_path = salt.utils.files.mkstemp()
with salt.utils.files.fopen(cron_path, 'w+') as fp_:
raw_cron = __salt__['cron.raw_cron'](user)
if not raw_cron.endswith('\n'):
raw_cron = "{0}\n".format(raw_cron)
fp_.write(salt.utils.stringutils.to_str(raw_cron))
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
# Avoid variable naming confusion in below module calls, since ID
# declaration for this state will be a source URI.
source = name
if not replace and os.stat(cron_path).st_size > 0:
ret['comment'] = 'User {0} already has a crontab. No changes ' \
'made'.format(user)
os.unlink(cron_path)
return ret
if __opts__['test']:
fcm = __salt__['file.check_managed'](name=cron_path,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[], # no special attrs for cron
template=template,
context=context,
defaults=defaults,
saltenv=__env__,
**kwargs
)
ret['result'], ret['comment'] = fcm
os.unlink(cron_path)
return ret
# If the source is a list then find which file exists
source, source_hash = __salt__['file.source_list'](source,
source_hash,
__env__)
# Gather the source file from the server
try:
sfn, source_sum, comment = __salt__['file.get_managed'](
name=cron_path,
template=template,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
context=context,
defaults=defaults,
skip_verify=False, # skip_verify
**kwargs
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
if comment:
ret['comment'] = comment
ret['result'] = False
os.unlink(cron_path)
return ret
try:
ret = __salt__['file.manage_file'](
name=cron_path,
sfn=sfn,
ret=ret,
source=source,
source_sum=source_sum,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
backup=backup
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
cron_ret = None
if "diff" in ret['changes']:
cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path)
# Check cmd return code and show success or failure
if cron_ret['retcode'] == 0:
ret['comment'] = 'Crontab for user {0} was updated'.format(user)
ret['result'] = True
ret['changes'] = ret['changes']
else:
ret['comment'] = 'Unable to update user {0} crontab {1}.' \
' Error: {2}'.format(user, cron_path, cron_ret['stderr'])
ret['result'] = False
ret['changes'] = {}
elif ret['result']:
ret['comment'] = 'Crontab for user {0} is in the correct ' \
'state'.format(user)
ret['changes'] = {}
os.unlink(cron_path)
return ret
def env_present(name,
value=None,
user='root'):
'''
Verifies that the specified environment variable is present in the crontab
for the specified user.
name
The name of the environment variable to set in the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
value
The value to set for the given environment variable
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron_env(user, name, value=value)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron env {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron env {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron env {0} is set to be updated'.format(name)
return ret
data = __salt__['cron.set_env'](user, name, value=value)
if data == 'present':
ret['comment'] = 'Cron env {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron env {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron env {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron env {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def env_absent(name,
user='root'):
'''
Verifies that the specified environment variable is absent from the crontab
for the specified user
name
The name of the environment variable to remove from the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
'''
name = name.strip()
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron_env(user, name)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron env {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron env {0} is set to be removed'.format(name)
return ret
data = __salt__['cron.rm_env'](user, name)
if data == 'absent':
ret['comment'] = "Cron env {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron env {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron env {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/cron.py
|
absent
|
python
|
def absent(name,
user='root',
identifier=False,
special=None,
**kwargs):
'''
Verifies that the specified cron job is absent for the specified user; only
the name is matched when removing a cron job.
name
The command that should be absent in the user crontab.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
The special keyword used in the job (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
'''
# NOTE: The keyword arguments in **kwargs are ignored in this state, but
# cannot be removed from the function definition, otherwise the use
# of unsupported arguments will result in a traceback.
name = name.strip()
if identifier is False:
identifier = name
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron(user, name, identifier=identifier)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron {0} is set to be removed'.format(name)
return ret
if special is None:
data = __salt__['cron.rm_job'](user, name, identifier=identifier)
else:
data = __salt__['cron.rm_special'](user, name, special=special, identifier=identifier)
if data == 'absent':
ret['comment'] = "Cron {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
|
Verifies that the specified cron job is absent for the specified user; only
the name is matched when removing a cron job.
name
The command that should be absent in the user crontab.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
The special keyword used in the job (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L386-L448
|
[
"def _check_cron(user,\n cmd,\n minute=None,\n hour=None,\n daymonth=None,\n month=None,\n dayweek=None,\n comment=None,\n commented=None,\n identifier=None,\n special=None):\n '''\n Return the changes\n '''\n if minute is not None:\n minute = six.text_type(minute).lower()\n if hour is not None:\n hour = six.text_type(hour).lower()\n if daymonth is not None:\n daymonth = six.text_type(daymonth).lower()\n if month is not None:\n month = six.text_type(month).lower()\n if dayweek is not None:\n dayweek = six.text_type(dayweek).lower()\n if identifier is not None:\n identifier = six.text_type(identifier)\n if commented is not None:\n commented = commented is True\n if cmd is not None:\n cmd = six.text_type(cmd)\n lst = __salt__['cron.list_tab'](user)\n if special is None:\n for cron in lst['crons']:\n if _cron_matched(cron, cmd, identifier):\n if any([_needs_change(x, y) for x, y in\n ((cron['minute'], minute), (cron['hour'], hour),\n (cron['daymonth'], daymonth), (cron['month'], month),\n (cron['dayweek'], dayweek), (cron['identifier'], identifier),\n (cron['cmd'], cmd), (cron['comment'], comment),\n (cron['commented'], commented))]):\n return 'update'\n return 'present'\n else:\n for cron in lst['special']:\n if _cron_matched(cron, cmd, identifier):\n if any([_needs_change(x, y) for x, y in\n ((cron['spec'], special),\n (cron['identifier'], identifier),\n (cron['cmd'], cmd),\n (cron['comment'], comment),\n (cron['commented'], commented))]):\n return 'update'\n return 'present'\n return 'absent'\n"
] |
# -*- coding: utf-8 -*-
'''
Management of cron, the Unix command scheduler
==============================================
Cron declarations require a number of parameters. The following are the
parameters used by Salt to define the various timing values for a cron job:
* ``minute``
* ``hour``
* ``daymonth``
* ``month``
* ``dayweek`` (0 to 6 are Sunday through Saturday, 7 can also be used for
Sunday)
.. warning::
Any timing arguments not specified take a value of ``*``. This means that
setting ``hour`` to ``5``, while not defining the ``minute`` param, will
result in Salt adding a job that will execute every minute between 5 and 6
A.M.!
Additionally, the default user for these states is ``root``. Therefore, if
the cron job is for another user, it is necessary to specify that user with
the ``user`` parameter.
A long time ago (before 2014.2), when making changes to an existing cron job,
the name declaration is the parameter used to uniquely identify the job,
so if an existing cron that looks like this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 5
Is changed to this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 7
- hour: 2
Then the existing cron will be updated, but if the cron command is changed,
then a new cron job will be added to the user's crontab.
The current behavior is still relying on that mechanism, but you can also
specify an identifier to identify your crontabs:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 7
- hour: 2
.. versionadded:: 2014.1.2
And, some months later, you modify it:
.. code-block:: yaml
superscript > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 3
- hour: 4
.. versionadded:: 2014.1.2
The old **date > /tmp/crontest** will be replaced by
**superscript > /tmp/crontest**.
Additionally, Salt also supports running a cron every ``x minutes`` very similarly to the Unix
convention of using ``*/5`` to have a job run every five minutes. In Salt, this
looks like:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: '*/5'
The job will now run every 5 minutes.
Additionally, the temporal parameters (minute, hour, etc.) can be randomized by
using ``random`` instead of using a specific value. For example, by using the
``random`` keyword in the ``minute`` parameter of a cron state, the same cron
job can be pushed to hundreds or thousands of hosts, and they would each use a
randomly-generated minute. This can be helpful when the cron job accesses a
network resource, and it is not desirable for all hosts to run the job
concurrently.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- minute: random
- hour: 2
.. versionadded:: 0.16.0
Since Salt assumes a value of ``*`` for unspecified temporal parameters, adding
a parameter to the state and setting it to ``random`` will change that value
from ``*`` to a randomized numeric value. However, if that field in the cron
entry on the minion already contains a numeric value, then using the ``random``
keyword will not modify it.
Added the opportunity to set a job with a special keyword like '@reboot' or
'@hourly'. Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- special: '@hourly'
The script will be executed every reboot if cron daemon support this option.
.. code-block:: yaml
/path/to/cron/otherscript:
cron.absent:
- user: root
- special: '@daily'
This counter part definition will ensure than a job with a special keyword
is not set.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
# Import salt libs
import salt.utils.files
from salt.modules.cron import (
_needs_change,
_cron_matched
)
from salt.ext import six
def __virtual__():
if 'cron.list_tab' in __salt__:
return True
else:
return (False, 'cron module could not be loaded')
def _check_cron(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
comment=None,
commented=None,
identifier=None,
special=None):
'''
Return the changes
'''
if minute is not None:
minute = six.text_type(minute).lower()
if hour is not None:
hour = six.text_type(hour).lower()
if daymonth is not None:
daymonth = six.text_type(daymonth).lower()
if month is not None:
month = six.text_type(month).lower()
if dayweek is not None:
dayweek = six.text_type(dayweek).lower()
if identifier is not None:
identifier = six.text_type(identifier)
if commented is not None:
commented = commented is True
if cmd is not None:
cmd = six.text_type(cmd)
lst = __salt__['cron.list_tab'](user)
if special is None:
for cron in lst['crons']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['minute'], minute), (cron['hour'], hour),
(cron['daymonth'], daymonth), (cron['month'], month),
(cron['dayweek'], dayweek), (cron['identifier'], identifier),
(cron['cmd'], cmd), (cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
else:
for cron in lst['special']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['spec'], special),
(cron['identifier'], identifier),
(cron['cmd'], cmd),
(cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
return 'absent'
def _check_cron_env(user,
name,
value=None):
'''
Return the environment changes
'''
if value is None:
value = "" # Matching value set in salt.modules.cron._render_tab
lst = __salt__['cron.list_tab'](user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
return 'update'
return 'present'
return 'absent'
def _get_cron_info():
'''
Returns the proper group owner and path to the cron directory
'''
owner = 'root'
if __grains__['os'] == 'FreeBSD':
group = 'wheel'
crontab_dir = '/var/cron/tabs'
elif __grains__['os'] == 'OpenBSD':
group = 'crontab'
crontab_dir = '/var/cron/tabs'
elif __grains__['os_family'] == 'Solaris':
group = 'root'
crontab_dir = '/var/spool/cron/crontabs'
elif __grains__['os'] == 'MacOS':
group = 'wheel'
crontab_dir = '/usr/lib/cron/tabs'
else:
group = 'root'
crontab_dir = '/var/spool/cron'
return owner, group, crontab_dir
def present(name,
user='root',
minute='*',
hour='*',
daymonth='*',
month='*',
dayweek='*',
comment=None,
commented=False,
identifier=False,
special=None):
'''
Verifies that the specified cron job is present for the specified user.
It is recommended to use `identifier`. Otherwise the cron job is installed
twice if you change the name.
For more advanced information about what exactly can be set in the cron
timing parameters, check your cron system's documentation. Most Unix-like
systems' cron documentation can be found via the crontab man page:
``man 5 crontab``.
name
The command that should be executed by the cron job.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
minute
The information to be set into the minute section, this can be any
string supported by your cron system's the minute field. Default is
``*``
hour
The information to be set in the hour section. Default is ``*``
daymonth
The information to be set in the day of month section. Default is ``*``
month
The information to be set in the month section. Default is ``*``
dayweek
The information to be set in the day of week section. Default is ``*``
comment
User comment to be added on line previous the cron job
commented
The cron job is set commented (prefixed with ``#DISABLED#``).
Defaults to False.
.. versionadded:: 2016.3.0
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
A special keyword to specify periodicity (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. versionadded:: 2016.3.0
'''
name = name.strip()
if identifier is False:
identifier = name
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron(user,
cmd=name,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
comment=comment,
commented=commented,
identifier=identifier,
special=special)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron {0} is set to be updated'.format(name)
return ret
if special is None:
data = __salt__['cron.set_job'](user=user,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
else:
data = __salt__['cron.set_special'](user=user,
special=special,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
if data == 'present':
ret['comment'] = 'Cron {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def file(name,
source_hash='',
source_hash_name=None,
user='root',
template=None,
context=None,
replace=True,
defaults=None,
backup='',
**kwargs):
'''
Provides file.managed-like functionality (templating, etc.) for a pre-made
crontab file, to be assigned to a given user.
name
The source file to be used as the crontab. This source file can be
hosted on either the salt master server, or on an HTTP or FTP server.
For files hosted on the salt file server, if the file is located on
the master in the directory named spam, and is called eggs, the source
string is ``salt://spam/eggs``
If the file is hosted on a HTTP or FTP server then the source_hash
argument is also required
source_hash
This can be either a file which contains a source hash string for
the source, or a source hash string. The source hash string is the
hash algorithm followed by the hash of the file:
``md5=e138491e9d5b97023cea823fe17bac22``
source_hash_name
When ``source_hash`` refers to a hash file, Salt will try to find the
correct hash by matching the filename/URI associated with that hash. By
default, Salt will look for the filename being managed. When managing a
file at path ``/tmp/foo.txt``, then the following line in a hash file
would match:
.. code-block:: text
acbd18db4cc2f85cedef654fccc4a4d8 foo.txt
However, sometimes a hash file will include multiple similar paths:
.. code-block:: text
37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt
acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt
73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt
In cases like this, Salt may match the incorrect hash. This argument
can be used to tell Salt which filename to match, to ensure that the
correct hash is identified. For example:
.. code-block:: yaml
foo_crontab:
cron.file:
- name: https://mydomain.tld/dir2/foo.txt
- source_hash: https://mydomain.tld/hashes
- source_hash_name: ./dir2/foo.txt
.. note::
This argument must contain the full filename entry from the
checksum file, as this argument is meant to disambiguate matches
for multiple files that have the same basename. So, in the
example above, simply using ``foo.txt`` would not match.
.. versionadded:: 2016.3.5
user
The user to whom the crontab should be assigned. This defaults to
root.
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently, jinja and mako are
supported.
context
Overrides default context variables passed to the template.
replace
If the crontab should be replaced, if False then this command will
be ignored if a crontab exists for the specified user. Default is True.
defaults
Default context passed to the template.
backup
Overrides the default backup mode for the user's crontab.
'''
# Initial set up
mode = '0600'
try:
group = __salt__['user.info'](user)['groups'][0]
except Exception:
ret = {'changes': {},
'comment': "Could not identify group for user {0}".format(user),
'name': name,
'result': False}
return ret
cron_path = salt.utils.files.mkstemp()
with salt.utils.files.fopen(cron_path, 'w+') as fp_:
raw_cron = __salt__['cron.raw_cron'](user)
if not raw_cron.endswith('\n'):
raw_cron = "{0}\n".format(raw_cron)
fp_.write(salt.utils.stringutils.to_str(raw_cron))
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
# Avoid variable naming confusion in below module calls, since ID
# declaration for this state will be a source URI.
source = name
if not replace and os.stat(cron_path).st_size > 0:
ret['comment'] = 'User {0} already has a crontab. No changes ' \
'made'.format(user)
os.unlink(cron_path)
return ret
if __opts__['test']:
fcm = __salt__['file.check_managed'](name=cron_path,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[], # no special attrs for cron
template=template,
context=context,
defaults=defaults,
saltenv=__env__,
**kwargs
)
ret['result'], ret['comment'] = fcm
os.unlink(cron_path)
return ret
# If the source is a list then find which file exists
source, source_hash = __salt__['file.source_list'](source,
source_hash,
__env__)
# Gather the source file from the server
try:
sfn, source_sum, comment = __salt__['file.get_managed'](
name=cron_path,
template=template,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
context=context,
defaults=defaults,
skip_verify=False, # skip_verify
**kwargs
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
if comment:
ret['comment'] = comment
ret['result'] = False
os.unlink(cron_path)
return ret
try:
ret = __salt__['file.manage_file'](
name=cron_path,
sfn=sfn,
ret=ret,
source=source,
source_sum=source_sum,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
backup=backup
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
cron_ret = None
if "diff" in ret['changes']:
cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path)
# Check cmd return code and show success or failure
if cron_ret['retcode'] == 0:
ret['comment'] = 'Crontab for user {0} was updated'.format(user)
ret['result'] = True
ret['changes'] = ret['changes']
else:
ret['comment'] = 'Unable to update user {0} crontab {1}.' \
' Error: {2}'.format(user, cron_path, cron_ret['stderr'])
ret['result'] = False
ret['changes'] = {}
elif ret['result']:
ret['comment'] = 'Crontab for user {0} is in the correct ' \
'state'.format(user)
ret['changes'] = {}
os.unlink(cron_path)
return ret
def env_present(name,
value=None,
user='root'):
'''
Verifies that the specified environment variable is present in the crontab
for the specified user.
name
The name of the environment variable to set in the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
value
The value to set for the given environment variable
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron_env(user, name, value=value)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron env {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron env {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron env {0} is set to be updated'.format(name)
return ret
data = __salt__['cron.set_env'](user, name, value=value)
if data == 'present':
ret['comment'] = 'Cron env {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron env {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron env {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron env {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def env_absent(name,
user='root'):
'''
Verifies that the specified environment variable is absent from the crontab
for the specified user
name
The name of the environment variable to remove from the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
'''
name = name.strip()
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron_env(user, name)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron env {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron env {0} is set to be removed'.format(name)
return ret
data = __salt__['cron.rm_env'](user, name)
if data == 'absent':
ret['comment'] = "Cron env {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron env {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron env {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/cron.py
|
file
|
python
|
def file(name,
source_hash='',
source_hash_name=None,
user='root',
template=None,
context=None,
replace=True,
defaults=None,
backup='',
**kwargs):
'''
Provides file.managed-like functionality (templating, etc.) for a pre-made
crontab file, to be assigned to a given user.
name
The source file to be used as the crontab. This source file can be
hosted on either the salt master server, or on an HTTP or FTP server.
For files hosted on the salt file server, if the file is located on
the master in the directory named spam, and is called eggs, the source
string is ``salt://spam/eggs``
If the file is hosted on a HTTP or FTP server then the source_hash
argument is also required
source_hash
This can be either a file which contains a source hash string for
the source, or a source hash string. The source hash string is the
hash algorithm followed by the hash of the file:
``md5=e138491e9d5b97023cea823fe17bac22``
source_hash_name
When ``source_hash`` refers to a hash file, Salt will try to find the
correct hash by matching the filename/URI associated with that hash. By
default, Salt will look for the filename being managed. When managing a
file at path ``/tmp/foo.txt``, then the following line in a hash file
would match:
.. code-block:: text
acbd18db4cc2f85cedef654fccc4a4d8 foo.txt
However, sometimes a hash file will include multiple similar paths:
.. code-block:: text
37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt
acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt
73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt
In cases like this, Salt may match the incorrect hash. This argument
can be used to tell Salt which filename to match, to ensure that the
correct hash is identified. For example:
.. code-block:: yaml
foo_crontab:
cron.file:
- name: https://mydomain.tld/dir2/foo.txt
- source_hash: https://mydomain.tld/hashes
- source_hash_name: ./dir2/foo.txt
.. note::
This argument must contain the full filename entry from the
checksum file, as this argument is meant to disambiguate matches
for multiple files that have the same basename. So, in the
example above, simply using ``foo.txt`` would not match.
.. versionadded:: 2016.3.5
user
The user to whom the crontab should be assigned. This defaults to
root.
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently, jinja and mako are
supported.
context
Overrides default context variables passed to the template.
replace
If the crontab should be replaced, if False then this command will
be ignored if a crontab exists for the specified user. Default is True.
defaults
Default context passed to the template.
backup
Overrides the default backup mode for the user's crontab.
'''
# Initial set up
mode = '0600'
try:
group = __salt__['user.info'](user)['groups'][0]
except Exception:
ret = {'changes': {},
'comment': "Could not identify group for user {0}".format(user),
'name': name,
'result': False}
return ret
cron_path = salt.utils.files.mkstemp()
with salt.utils.files.fopen(cron_path, 'w+') as fp_:
raw_cron = __salt__['cron.raw_cron'](user)
if not raw_cron.endswith('\n'):
raw_cron = "{0}\n".format(raw_cron)
fp_.write(salt.utils.stringutils.to_str(raw_cron))
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
# Avoid variable naming confusion in below module calls, since ID
# declaration for this state will be a source URI.
source = name
if not replace and os.stat(cron_path).st_size > 0:
ret['comment'] = 'User {0} already has a crontab. No changes ' \
'made'.format(user)
os.unlink(cron_path)
return ret
if __opts__['test']:
fcm = __salt__['file.check_managed'](name=cron_path,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[], # no special attrs for cron
template=template,
context=context,
defaults=defaults,
saltenv=__env__,
**kwargs
)
ret['result'], ret['comment'] = fcm
os.unlink(cron_path)
return ret
# If the source is a list then find which file exists
source, source_hash = __salt__['file.source_list'](source,
source_hash,
__env__)
# Gather the source file from the server
try:
sfn, source_sum, comment = __salt__['file.get_managed'](
name=cron_path,
template=template,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
context=context,
defaults=defaults,
skip_verify=False, # skip_verify
**kwargs
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
if comment:
ret['comment'] = comment
ret['result'] = False
os.unlink(cron_path)
return ret
try:
ret = __salt__['file.manage_file'](
name=cron_path,
sfn=sfn,
ret=ret,
source=source,
source_sum=source_sum,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
backup=backup
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
cron_ret = None
if "diff" in ret['changes']:
cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path)
# Check cmd return code and show success or failure
if cron_ret['retcode'] == 0:
ret['comment'] = 'Crontab for user {0} was updated'.format(user)
ret['result'] = True
ret['changes'] = ret['changes']
else:
ret['comment'] = 'Unable to update user {0} crontab {1}.' \
' Error: {2}'.format(user, cron_path, cron_ret['stderr'])
ret['result'] = False
ret['changes'] = {}
elif ret['result']:
ret['comment'] = 'Crontab for user {0} is in the correct ' \
'state'.format(user)
ret['changes'] = {}
os.unlink(cron_path)
return ret
|
Provides file.managed-like functionality (templating, etc.) for a pre-made
crontab file, to be assigned to a given user.
name
The source file to be used as the crontab. This source file can be
hosted on either the salt master server, or on an HTTP or FTP server.
For files hosted on the salt file server, if the file is located on
the master in the directory named spam, and is called eggs, the source
string is ``salt://spam/eggs``
If the file is hosted on a HTTP or FTP server then the source_hash
argument is also required
source_hash
This can be either a file which contains a source hash string for
the source, or a source hash string. The source hash string is the
hash algorithm followed by the hash of the file:
``md5=e138491e9d5b97023cea823fe17bac22``
source_hash_name
When ``source_hash`` refers to a hash file, Salt will try to find the
correct hash by matching the filename/URI associated with that hash. By
default, Salt will look for the filename being managed. When managing a
file at path ``/tmp/foo.txt``, then the following line in a hash file
would match:
.. code-block:: text
acbd18db4cc2f85cedef654fccc4a4d8 foo.txt
However, sometimes a hash file will include multiple similar paths:
.. code-block:: text
37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt
acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt
73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt
In cases like this, Salt may match the incorrect hash. This argument
can be used to tell Salt which filename to match, to ensure that the
correct hash is identified. For example:
.. code-block:: yaml
foo_crontab:
cron.file:
- name: https://mydomain.tld/dir2/foo.txt
- source_hash: https://mydomain.tld/hashes
- source_hash_name: ./dir2/foo.txt
.. note::
This argument must contain the full filename entry from the
checksum file, as this argument is meant to disambiguate matches
for multiple files that have the same basename. So, in the
example above, simply using ``foo.txt`` would not match.
.. versionadded:: 2016.3.5
user
The user to whom the crontab should be assigned. This defaults to
root.
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently, jinja and mako are
supported.
context
Overrides default context variables passed to the template.
replace
If the crontab should be replaced, if False then this command will
be ignored if a crontab exists for the specified user. Default is True.
defaults
Default context passed to the template.
backup
Overrides the default backup mode for the user's crontab.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L451-L669
|
[
"def mkstemp(*args, **kwargs):\n '''\n Helper function which does exactly what ``tempfile.mkstemp()`` does but\n accepts another argument, ``close_fd``, which, by default, is true and closes\n the fd before returning the file path. Something commonly done throughout\n Salt's code.\n '''\n if 'prefix' not in kwargs:\n kwargs['prefix'] = '__salt.tmp.'\n close_fd = kwargs.pop('close_fd', True)\n fd_, f_path = tempfile.mkstemp(*args, **kwargs)\n if close_fd is False:\n return fd_, f_path\n os.close(fd_)\n del fd_\n return f_path\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 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"
] |
# -*- coding: utf-8 -*-
'''
Management of cron, the Unix command scheduler
==============================================
Cron declarations require a number of parameters. The following are the
parameters used by Salt to define the various timing values for a cron job:
* ``minute``
* ``hour``
* ``daymonth``
* ``month``
* ``dayweek`` (0 to 6 are Sunday through Saturday, 7 can also be used for
Sunday)
.. warning::
Any timing arguments not specified take a value of ``*``. This means that
setting ``hour`` to ``5``, while not defining the ``minute`` param, will
result in Salt adding a job that will execute every minute between 5 and 6
A.M.!
Additionally, the default user for these states is ``root``. Therefore, if
the cron job is for another user, it is necessary to specify that user with
the ``user`` parameter.
A long time ago (before 2014.2), when making changes to an existing cron job,
the name declaration is the parameter used to uniquely identify the job,
so if an existing cron that looks like this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 5
Is changed to this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 7
- hour: 2
Then the existing cron will be updated, but if the cron command is changed,
then a new cron job will be added to the user's crontab.
The current behavior is still relying on that mechanism, but you can also
specify an identifier to identify your crontabs:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 7
- hour: 2
.. versionadded:: 2014.1.2
And, some months later, you modify it:
.. code-block:: yaml
superscript > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 3
- hour: 4
.. versionadded:: 2014.1.2
The old **date > /tmp/crontest** will be replaced by
**superscript > /tmp/crontest**.
Additionally, Salt also supports running a cron every ``x minutes`` very similarly to the Unix
convention of using ``*/5`` to have a job run every five minutes. In Salt, this
looks like:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: '*/5'
The job will now run every 5 minutes.
Additionally, the temporal parameters (minute, hour, etc.) can be randomized by
using ``random`` instead of using a specific value. For example, by using the
``random`` keyword in the ``minute`` parameter of a cron state, the same cron
job can be pushed to hundreds or thousands of hosts, and they would each use a
randomly-generated minute. This can be helpful when the cron job accesses a
network resource, and it is not desirable for all hosts to run the job
concurrently.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- minute: random
- hour: 2
.. versionadded:: 0.16.0
Since Salt assumes a value of ``*`` for unspecified temporal parameters, adding
a parameter to the state and setting it to ``random`` will change that value
from ``*`` to a randomized numeric value. However, if that field in the cron
entry on the minion already contains a numeric value, then using the ``random``
keyword will not modify it.
Added the opportunity to set a job with a special keyword like '@reboot' or
'@hourly'. Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- special: '@hourly'
The script will be executed every reboot if cron daemon support this option.
.. code-block:: yaml
/path/to/cron/otherscript:
cron.absent:
- user: root
- special: '@daily'
This counter part definition will ensure than a job with a special keyword
is not set.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
# Import salt libs
import salt.utils.files
from salt.modules.cron import (
_needs_change,
_cron_matched
)
from salt.ext import six
def __virtual__():
if 'cron.list_tab' in __salt__:
return True
else:
return (False, 'cron module could not be loaded')
def _check_cron(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
comment=None,
commented=None,
identifier=None,
special=None):
'''
Return the changes
'''
if minute is not None:
minute = six.text_type(minute).lower()
if hour is not None:
hour = six.text_type(hour).lower()
if daymonth is not None:
daymonth = six.text_type(daymonth).lower()
if month is not None:
month = six.text_type(month).lower()
if dayweek is not None:
dayweek = six.text_type(dayweek).lower()
if identifier is not None:
identifier = six.text_type(identifier)
if commented is not None:
commented = commented is True
if cmd is not None:
cmd = six.text_type(cmd)
lst = __salt__['cron.list_tab'](user)
if special is None:
for cron in lst['crons']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['minute'], minute), (cron['hour'], hour),
(cron['daymonth'], daymonth), (cron['month'], month),
(cron['dayweek'], dayweek), (cron['identifier'], identifier),
(cron['cmd'], cmd), (cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
else:
for cron in lst['special']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['spec'], special),
(cron['identifier'], identifier),
(cron['cmd'], cmd),
(cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
return 'absent'
def _check_cron_env(user,
name,
value=None):
'''
Return the environment changes
'''
if value is None:
value = "" # Matching value set in salt.modules.cron._render_tab
lst = __salt__['cron.list_tab'](user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
return 'update'
return 'present'
return 'absent'
def _get_cron_info():
'''
Returns the proper group owner and path to the cron directory
'''
owner = 'root'
if __grains__['os'] == 'FreeBSD':
group = 'wheel'
crontab_dir = '/var/cron/tabs'
elif __grains__['os'] == 'OpenBSD':
group = 'crontab'
crontab_dir = '/var/cron/tabs'
elif __grains__['os_family'] == 'Solaris':
group = 'root'
crontab_dir = '/var/spool/cron/crontabs'
elif __grains__['os'] == 'MacOS':
group = 'wheel'
crontab_dir = '/usr/lib/cron/tabs'
else:
group = 'root'
crontab_dir = '/var/spool/cron'
return owner, group, crontab_dir
def present(name,
user='root',
minute='*',
hour='*',
daymonth='*',
month='*',
dayweek='*',
comment=None,
commented=False,
identifier=False,
special=None):
'''
Verifies that the specified cron job is present for the specified user.
It is recommended to use `identifier`. Otherwise the cron job is installed
twice if you change the name.
For more advanced information about what exactly can be set in the cron
timing parameters, check your cron system's documentation. Most Unix-like
systems' cron documentation can be found via the crontab man page:
``man 5 crontab``.
name
The command that should be executed by the cron job.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
minute
The information to be set into the minute section, this can be any
string supported by your cron system's the minute field. Default is
``*``
hour
The information to be set in the hour section. Default is ``*``
daymonth
The information to be set in the day of month section. Default is ``*``
month
The information to be set in the month section. Default is ``*``
dayweek
The information to be set in the day of week section. Default is ``*``
comment
User comment to be added on line previous the cron job
commented
The cron job is set commented (prefixed with ``#DISABLED#``).
Defaults to False.
.. versionadded:: 2016.3.0
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
A special keyword to specify periodicity (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. versionadded:: 2016.3.0
'''
name = name.strip()
if identifier is False:
identifier = name
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron(user,
cmd=name,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
comment=comment,
commented=commented,
identifier=identifier,
special=special)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron {0} is set to be updated'.format(name)
return ret
if special is None:
data = __salt__['cron.set_job'](user=user,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
else:
data = __salt__['cron.set_special'](user=user,
special=special,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
if data == 'present':
ret['comment'] = 'Cron {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def absent(name,
user='root',
identifier=False,
special=None,
**kwargs):
'''
Verifies that the specified cron job is absent for the specified user; only
the name is matched when removing a cron job.
name
The command that should be absent in the user crontab.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
The special keyword used in the job (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
'''
# NOTE: The keyword arguments in **kwargs are ignored in this state, but
# cannot be removed from the function definition, otherwise the use
# of unsupported arguments will result in a traceback.
name = name.strip()
if identifier is False:
identifier = name
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron(user, name, identifier=identifier)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron {0} is set to be removed'.format(name)
return ret
if special is None:
data = __salt__['cron.rm_job'](user, name, identifier=identifier)
else:
data = __salt__['cron.rm_special'](user, name, special=special, identifier=identifier)
if data == 'absent':
ret['comment'] = "Cron {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
def env_present(name,
value=None,
user='root'):
'''
Verifies that the specified environment variable is present in the crontab
for the specified user.
name
The name of the environment variable to set in the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
value
The value to set for the given environment variable
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron_env(user, name, value=value)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron env {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron env {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron env {0} is set to be updated'.format(name)
return ret
data = __salt__['cron.set_env'](user, name, value=value)
if data == 'present':
ret['comment'] = 'Cron env {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron env {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron env {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron env {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def env_absent(name,
user='root'):
'''
Verifies that the specified environment variable is absent from the crontab
for the specified user
name
The name of the environment variable to remove from the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
'''
name = name.strip()
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron_env(user, name)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron env {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron env {0} is set to be removed'.format(name)
return ret
data = __salt__['cron.rm_env'](user, name)
if data == 'absent':
ret['comment'] = "Cron env {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron env {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron env {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/cron.py
|
env_present
|
python
|
def env_present(name,
value=None,
user='root'):
'''
Verifies that the specified environment variable is present in the crontab
for the specified user.
name
The name of the environment variable to set in the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
value
The value to set for the given environment variable
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron_env(user, name, value=value)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron env {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron env {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron env {0} is set to be updated'.format(name)
return ret
data = __salt__['cron.set_env'](user, name, value=value)
if data == 'present':
ret['comment'] = 'Cron env {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron env {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron env {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron env {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
|
Verifies that the specified environment variable is present in the crontab
for the specified user.
name
The name of the environment variable to set in the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
value
The value to set for the given environment variable
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L672-L722
|
[
"def _check_cron_env(user,\n name,\n value=None):\n '''\n Return the environment changes\n '''\n if value is None:\n value = \"\" # Matching value set in salt.modules.cron._render_tab\n lst = __salt__['cron.list_tab'](user)\n for env in lst['env']:\n if name == env['name']:\n if value != env['value']:\n return 'update'\n return 'present'\n return 'absent'\n"
] |
# -*- coding: utf-8 -*-
'''
Management of cron, the Unix command scheduler
==============================================
Cron declarations require a number of parameters. The following are the
parameters used by Salt to define the various timing values for a cron job:
* ``minute``
* ``hour``
* ``daymonth``
* ``month``
* ``dayweek`` (0 to 6 are Sunday through Saturday, 7 can also be used for
Sunday)
.. warning::
Any timing arguments not specified take a value of ``*``. This means that
setting ``hour`` to ``5``, while not defining the ``minute`` param, will
result in Salt adding a job that will execute every minute between 5 and 6
A.M.!
Additionally, the default user for these states is ``root``. Therefore, if
the cron job is for another user, it is necessary to specify that user with
the ``user`` parameter.
A long time ago (before 2014.2), when making changes to an existing cron job,
the name declaration is the parameter used to uniquely identify the job,
so if an existing cron that looks like this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 5
Is changed to this:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: 7
- hour: 2
Then the existing cron will be updated, but if the cron command is changed,
then a new cron job will be added to the user's crontab.
The current behavior is still relying on that mechanism, but you can also
specify an identifier to identify your crontabs:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 7
- hour: 2
.. versionadded:: 2014.1.2
And, some months later, you modify it:
.. code-block:: yaml
superscript > /tmp/crontest:
cron.present:
- identifier: SUPERCRON
- user: root
- minute: 3
- hour: 4
.. versionadded:: 2014.1.2
The old **date > /tmp/crontest** will be replaced by
**superscript > /tmp/crontest**.
Additionally, Salt also supports running a cron every ``x minutes`` very similarly to the Unix
convention of using ``*/5`` to have a job run every five minutes. In Salt, this
looks like:
.. code-block:: yaml
date > /tmp/crontest:
cron.present:
- user: root
- minute: '*/5'
The job will now run every 5 minutes.
Additionally, the temporal parameters (minute, hour, etc.) can be randomized by
using ``random`` instead of using a specific value. For example, by using the
``random`` keyword in the ``minute`` parameter of a cron state, the same cron
job can be pushed to hundreds or thousands of hosts, and they would each use a
randomly-generated minute. This can be helpful when the cron job accesses a
network resource, and it is not desirable for all hosts to run the job
concurrently.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- minute: random
- hour: 2
.. versionadded:: 0.16.0
Since Salt assumes a value of ``*`` for unspecified temporal parameters, adding
a parameter to the state and setting it to ``random`` will change that value
from ``*`` to a randomized numeric value. However, if that field in the cron
entry on the minion already contains a numeric value, then using the ``random``
keyword will not modify it.
Added the opportunity to set a job with a special keyword like '@reboot' or
'@hourly'. Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. code-block:: yaml
/path/to/cron/script:
cron.present:
- user: root
- special: '@hourly'
The script will be executed every reboot if cron daemon support this option.
.. code-block:: yaml
/path/to/cron/otherscript:
cron.absent:
- user: root
- special: '@daily'
This counter part definition will ensure than a job with a special keyword
is not set.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
# Import salt libs
import salt.utils.files
from salt.modules.cron import (
_needs_change,
_cron_matched
)
from salt.ext import six
def __virtual__():
if 'cron.list_tab' in __salt__:
return True
else:
return (False, 'cron module could not be loaded')
def _check_cron(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
comment=None,
commented=None,
identifier=None,
special=None):
'''
Return the changes
'''
if minute is not None:
minute = six.text_type(minute).lower()
if hour is not None:
hour = six.text_type(hour).lower()
if daymonth is not None:
daymonth = six.text_type(daymonth).lower()
if month is not None:
month = six.text_type(month).lower()
if dayweek is not None:
dayweek = six.text_type(dayweek).lower()
if identifier is not None:
identifier = six.text_type(identifier)
if commented is not None:
commented = commented is True
if cmd is not None:
cmd = six.text_type(cmd)
lst = __salt__['cron.list_tab'](user)
if special is None:
for cron in lst['crons']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['minute'], minute), (cron['hour'], hour),
(cron['daymonth'], daymonth), (cron['month'], month),
(cron['dayweek'], dayweek), (cron['identifier'], identifier),
(cron['cmd'], cmd), (cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
else:
for cron in lst['special']:
if _cron_matched(cron, cmd, identifier):
if any([_needs_change(x, y) for x, y in
((cron['spec'], special),
(cron['identifier'], identifier),
(cron['cmd'], cmd),
(cron['comment'], comment),
(cron['commented'], commented))]):
return 'update'
return 'present'
return 'absent'
def _check_cron_env(user,
name,
value=None):
'''
Return the environment changes
'''
if value is None:
value = "" # Matching value set in salt.modules.cron._render_tab
lst = __salt__['cron.list_tab'](user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
return 'update'
return 'present'
return 'absent'
def _get_cron_info():
'''
Returns the proper group owner and path to the cron directory
'''
owner = 'root'
if __grains__['os'] == 'FreeBSD':
group = 'wheel'
crontab_dir = '/var/cron/tabs'
elif __grains__['os'] == 'OpenBSD':
group = 'crontab'
crontab_dir = '/var/cron/tabs'
elif __grains__['os_family'] == 'Solaris':
group = 'root'
crontab_dir = '/var/spool/cron/crontabs'
elif __grains__['os'] == 'MacOS':
group = 'wheel'
crontab_dir = '/usr/lib/cron/tabs'
else:
group = 'root'
crontab_dir = '/var/spool/cron'
return owner, group, crontab_dir
def present(name,
user='root',
minute='*',
hour='*',
daymonth='*',
month='*',
dayweek='*',
comment=None,
commented=False,
identifier=False,
special=None):
'''
Verifies that the specified cron job is present for the specified user.
It is recommended to use `identifier`. Otherwise the cron job is installed
twice if you change the name.
For more advanced information about what exactly can be set in the cron
timing parameters, check your cron system's documentation. Most Unix-like
systems' cron documentation can be found via the crontab man page:
``man 5 crontab``.
name
The command that should be executed by the cron job.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
minute
The information to be set into the minute section, this can be any
string supported by your cron system's the minute field. Default is
``*``
hour
The information to be set in the hour section. Default is ``*``
daymonth
The information to be set in the day of month section. Default is ``*``
month
The information to be set in the month section. Default is ``*``
dayweek
The information to be set in the day of week section. Default is ``*``
comment
User comment to be added on line previous the cron job
commented
The cron job is set commented (prefixed with ``#DISABLED#``).
Defaults to False.
.. versionadded:: 2016.3.0
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
A special keyword to specify periodicity (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
.. versionadded:: 2016.3.0
'''
name = name.strip()
if identifier is False:
identifier = name
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if __opts__['test']:
status = _check_cron(user,
cmd=name,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
comment=comment,
commented=commented,
identifier=identifier,
special=special)
ret['result'] = None
if status == 'absent':
ret['comment'] = 'Cron {0} is set to be added'.format(name)
elif status == 'present':
ret['result'] = True
ret['comment'] = 'Cron {0} already present'.format(name)
elif status == 'update':
ret['comment'] = 'Cron {0} is set to be updated'.format(name)
return ret
if special is None:
data = __salt__['cron.set_job'](user=user,
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
else:
data = __salt__['cron.set_special'](user=user,
special=special,
cmd=name,
comment=comment,
commented=commented,
identifier=identifier)
if data == 'present':
ret['comment'] = 'Cron {0} already present'.format(name)
return ret
if data == 'new':
ret['comment'] = 'Cron {0} added to {1}\'s crontab'.format(name, user)
ret['changes'] = {user: name}
return ret
if data == 'updated':
ret['comment'] = 'Cron {0} updated'.format(name)
ret['changes'] = {user: name}
return ret
ret['comment'] = ('Cron {0} for user {1} failed to commit with error \n{2}'
.format(name, user, data))
ret['result'] = False
return ret
def absent(name,
user='root',
identifier=False,
special=None,
**kwargs):
'''
Verifies that the specified cron job is absent for the specified user; only
the name is matched when removing a cron job.
name
The command that should be absent in the user crontab.
user
The name of the user whose crontab needs to be modified, defaults to
the root user
identifier
Custom-defined identifier for tracking the cron line for future crontab
edits. This defaults to the state name
special
The special keyword used in the job (eg. @reboot, @hourly...).
Quotes must be used, otherwise PyYAML will strip the '@' sign.
'''
# NOTE: The keyword arguments in **kwargs are ignored in this state, but
# cannot be removed from the function definition, otherwise the use
# of unsupported arguments will result in a traceback.
name = name.strip()
if identifier is False:
identifier = name
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron(user, name, identifier=identifier)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron {0} is set to be removed'.format(name)
return ret
if special is None:
data = __salt__['cron.rm_job'](user, name, identifier=identifier)
else:
data = __salt__['cron.rm_special'](user, name, special=special, identifier=identifier)
if data == 'absent':
ret['comment'] = "Cron {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
def file(name,
source_hash='',
source_hash_name=None,
user='root',
template=None,
context=None,
replace=True,
defaults=None,
backup='',
**kwargs):
'''
Provides file.managed-like functionality (templating, etc.) for a pre-made
crontab file, to be assigned to a given user.
name
The source file to be used as the crontab. This source file can be
hosted on either the salt master server, or on an HTTP or FTP server.
For files hosted on the salt file server, if the file is located on
the master in the directory named spam, and is called eggs, the source
string is ``salt://spam/eggs``
If the file is hosted on a HTTP or FTP server then the source_hash
argument is also required
source_hash
This can be either a file which contains a source hash string for
the source, or a source hash string. The source hash string is the
hash algorithm followed by the hash of the file:
``md5=e138491e9d5b97023cea823fe17bac22``
source_hash_name
When ``source_hash`` refers to a hash file, Salt will try to find the
correct hash by matching the filename/URI associated with that hash. By
default, Salt will look for the filename being managed. When managing a
file at path ``/tmp/foo.txt``, then the following line in a hash file
would match:
.. code-block:: text
acbd18db4cc2f85cedef654fccc4a4d8 foo.txt
However, sometimes a hash file will include multiple similar paths:
.. code-block:: text
37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt
acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt
73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt
In cases like this, Salt may match the incorrect hash. This argument
can be used to tell Salt which filename to match, to ensure that the
correct hash is identified. For example:
.. code-block:: yaml
foo_crontab:
cron.file:
- name: https://mydomain.tld/dir2/foo.txt
- source_hash: https://mydomain.tld/hashes
- source_hash_name: ./dir2/foo.txt
.. note::
This argument must contain the full filename entry from the
checksum file, as this argument is meant to disambiguate matches
for multiple files that have the same basename. So, in the
example above, simply using ``foo.txt`` would not match.
.. versionadded:: 2016.3.5
user
The user to whom the crontab should be assigned. This defaults to
root.
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently, jinja and mako are
supported.
context
Overrides default context variables passed to the template.
replace
If the crontab should be replaced, if False then this command will
be ignored if a crontab exists for the specified user. Default is True.
defaults
Default context passed to the template.
backup
Overrides the default backup mode for the user's crontab.
'''
# Initial set up
mode = '0600'
try:
group = __salt__['user.info'](user)['groups'][0]
except Exception:
ret = {'changes': {},
'comment': "Could not identify group for user {0}".format(user),
'name': name,
'result': False}
return ret
cron_path = salt.utils.files.mkstemp()
with salt.utils.files.fopen(cron_path, 'w+') as fp_:
raw_cron = __salt__['cron.raw_cron'](user)
if not raw_cron.endswith('\n'):
raw_cron = "{0}\n".format(raw_cron)
fp_.write(salt.utils.stringutils.to_str(raw_cron))
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
# Avoid variable naming confusion in below module calls, since ID
# declaration for this state will be a source URI.
source = name
if not replace and os.stat(cron_path).st_size > 0:
ret['comment'] = 'User {0} already has a crontab. No changes ' \
'made'.format(user)
os.unlink(cron_path)
return ret
if __opts__['test']:
fcm = __salt__['file.check_managed'](name=cron_path,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[], # no special attrs for cron
template=template,
context=context,
defaults=defaults,
saltenv=__env__,
**kwargs
)
ret['result'], ret['comment'] = fcm
os.unlink(cron_path)
return ret
# If the source is a list then find which file exists
source, source_hash = __salt__['file.source_list'](source,
source_hash,
__env__)
# Gather the source file from the server
try:
sfn, source_sum, comment = __salt__['file.get_managed'](
name=cron_path,
template=template,
source=source,
source_hash=source_hash,
source_hash_name=source_hash_name,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
context=context,
defaults=defaults,
skip_verify=False, # skip_verify
**kwargs
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
if comment:
ret['comment'] = comment
ret['result'] = False
os.unlink(cron_path)
return ret
try:
ret = __salt__['file.manage_file'](
name=cron_path,
sfn=sfn,
ret=ret,
source=source,
source_sum=source_sum,
user=user,
group=group,
mode=mode,
attrs=[],
saltenv=__env__,
backup=backup
)
except Exception as exc:
ret['result'] = False
ret['changes'] = {}
ret['comment'] = 'Unable to manage file: {0}'.format(exc)
return ret
cron_ret = None
if "diff" in ret['changes']:
cron_ret = __salt__['cron.write_cron_file_verbose'](user, cron_path)
# Check cmd return code and show success or failure
if cron_ret['retcode'] == 0:
ret['comment'] = 'Crontab for user {0} was updated'.format(user)
ret['result'] = True
ret['changes'] = ret['changes']
else:
ret['comment'] = 'Unable to update user {0} crontab {1}.' \
' Error: {2}'.format(user, cron_path, cron_ret['stderr'])
ret['result'] = False
ret['changes'] = {}
elif ret['result']:
ret['comment'] = 'Crontab for user {0} is in the correct ' \
'state'.format(user)
ret['changes'] = {}
os.unlink(cron_path)
return ret
def env_absent(name,
user='root'):
'''
Verifies that the specified environment variable is absent from the crontab
for the specified user
name
The name of the environment variable to remove from the user crontab
user
The name of the user whose crontab needs to be modified, defaults to
the root user
'''
name = name.strip()
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if __opts__['test']:
status = _check_cron_env(user, name)
ret['result'] = None
if status == 'absent':
ret['result'] = True
ret['comment'] = 'Cron env {0} is absent'.format(name)
elif status == 'present' or status == 'update':
ret['comment'] = 'Cron env {0} is set to be removed'.format(name)
return ret
data = __salt__['cron.rm_env'](user, name)
if data == 'absent':
ret['comment'] = "Cron env {0} already absent".format(name)
return ret
if data == 'removed':
ret['comment'] = ("Cron env {0} removed from {1}'s crontab"
.format(name, user))
ret['changes'] = {user: name}
return ret
ret['comment'] = ("Cron env {0} for user {1} failed to commit with error {2}"
.format(name, user, data))
ret['result'] = False
return ret
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.